I am creating a stored procedure to which I want to pass as variable a comma delimited list of Ids. I want to use the Ids into a select statement, something like:
Create Procedure up_TEST
@Ids VARCHAR(MAX)
AS
SELECT * FROM ATable a
WHERE a.Id IN(@Ids)
Obviously I get the error that @Ids
is a varchar and not an INT but how can I convert the comma delimited list?
Since you're using SQL Server 2008, have a look at table-valued parameters.
One way could be split and insert the ids into a tempory table and than use SQL IN clause...
If you're having this problem, you should read Sommarskog's articles.
http://www.sommarskog.se/index.html
I recommend:
Everyone seems to be doing something like this today!
Have a look at http://www.sqlteam.com/article/parsing-csv-values-into-multiple-rows - this is a way of processing a delimited input variable to give a results set containing the split items by joining against a numbers / tally table (which is a good thing to have in the database anyway if you haven't yet). This then gives you a simple results set which you can join against as per normal.
For those cases I use this table function, which you can adapt to your needs:
In your stored procedure you would use it like this:
Use a table values parameter (new in SQl Server 2008). Set it up by creating the actual table parameter type:
Your procedure would then be:
if you can't use table value parameters, see: "Arrays and Lists in SQL Server 2008 Using Table-Valued Parameters" by Erland Sommarskog , then there are many ways to split string in SQL Server. This article covers the PROs and CONs of just about every method:
"Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog
You need to create a split function. This is how a split function can be used:
I prefer the number table approach to split a string in TSQL but there are numerous ways to split strings in SQL Server, see the previous link, which explains the PROs and CONs of each.
For the Numbers Table method to work, you need to do this one time table setup, which will create a table
Numbers
that contains rows from 1 to 10,000:Once the Numbers table is set up, create this split function:
You can now easily split a CSV string into a table and join on it: