I have a C# app that passes in the following data:
datasetID = 10; userID = 1; varnames = \"\'ACT97\',\'ACTCHNG\',\'ACTQTR2\',\'ACTSCOR2\'\";
The stored procedur
There are several ways to accomplish this:
Dynamic SQL, as pointed out in this article: http://asheej.blogspot.com/2012/04/how-to-use-ms-sql-in-clause-with.html
Specify each item in variables (this can get quite ugly if you have a lot of 'em):
@var1 varchar(20), @var2 varchar(20), @var3 varchar(20)
Write a split function to turn the string into a table variable, there are many of them out there. This one is my personal favorite: http://dataeducation.com/faster-more-scalable-sqlclr-string-splitting/
Use a Table Value Parameter (2008): http://www.techrepublic.com/blog/datacenter/passing-table-valued-parameters-in-sql-server-2008/168
Here's a little trick using CHARINDEX (note that this approach is Non-Sargable):
Your string is like so: 'abc,def'
Using CHARINDEX
, you pad both the search string and value you want to find within the search string with your delimeter. So using my little example, the string would become ',abc,def,' Notice the extra commas at the beginning and end. Then do the same thing to the field data. If you have commas in your data, you'll have to swap out the delimeter to something else, like char(2), or semi-colons, or whatever.
Then to perform the search:
WHERE CHARINDEX ( ',' + expressionToFind + ',' , ',' + expressionToSearch ',') > 0
The delimeter padding keeps the search from finding "abcabc" but will find "abc", exact match.
If you're using 2005, I'd grab a really fast split function so you can avoid using dynamic SQL.