Duplicate of
Dynamic SQL Comma Delimited Value Query
Parameterized Queries with Like and In
I have a SQL Server Stored Procedure where I would like to pass a varchar
full of comma delimited values to an IN
function. For example:
DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN (@Ids);
This does not work of course. I get the error:
Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.
How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?
Try this:
As said on the last example of this link
No Table No Function No Loop
Building on the idea of parsing your list into a table our DBA suggested using XML.
These seems to have the same performance as @KM's answer but, I think, a lot simpler.
It's a very common question. Canned answer, several nice techniques:
http://www.sommarskog.se/arrays-in-sql-2005.html
I've written a stored procedure to show how to do this before. You basically have to process the string. I tried to post the code here but the formatting got all screwy.
Its been a while but I have done this in the past using XML as a interim.
I can't take any credit for this, but I'm afraid I no longer know where I got this idea from: