tags:

views:

41

answers:

3

How can I use a param for mulitple values in a "where in" query:

Select [..] where str in ('AB','BC')

Of course, this will not allow multiple values:

Select [..] where str in (@param)
+1  A: 

You need to add each param as a value in the IN clause, e.g.

where str in (@param1, @param2, @param3)

Alternately, you could create a query manually and EXEC it (though that's fraught with peril as well).

EDIT: So, just to clarify, since you're receiving a string of comma-delimited values that you then want to use in an IN clause, you'll need to do what astander suggested and split your string into a table which you could then use in the clause.

Using one of the links astander mentioned you could do the following:

select [...]
where str in (select items from dbo.split(@ItemString))

(where your comma-delimited values are in @ItemString).

Michael Todd
"You just can't argue with a word like fraught!" Tigger
Daniel Elliott
I think the OP might intend the params being in the single param such as @param = '''AB'',''BC'''
astander
Which will _not_ work unless the column contains that exact value (which it shouldn't).
Michael Todd
I think needs a split type function with a select in split function.
astander
Yes, I need a single param becouse there is a unkown number of values in the array. Is there maybe a way to expand a string like "AB|BC|CD"?
Francois Zbinden
Check out http://www.sommarskog.se/arrays-in-sql-2005.html for an analysis of the many possible split functions. Long, but well worth the read.
Tom H.
You could use Astander's solution to break the string up into individual rows and add them to a table, then write your query to join this table on the _str_ column. That will give you the results you're looking for (without having to resort to multiple param2 or manually written queries).
Michael Todd
+3  A: 

The alternative to adding each value as a separate param, if you are using SQL Server 2008, is to pass in a table valued parameter which would allow you to do something like:

SELECT...
FROM YourTable t
    JOIN @TableParam p ON t.str = p.str

If you're not using SQL 2008 and you actually want to pass all the values in as one CSV string, then the other common approach is to have a user defined function that splits the CSV string out and returns a TABLE which you can then join on, e.g.

SELECT ....
FROM YourTable t
    JOIN dbo.fnSplit(@param) s ON t.str = s.str
AdaTheDev
That's nice; wasn't aware of that.
Michael Todd
+1  A: 

OK, so you need a split function

SQL Server split function

and

Split Function in Sql Server to break Comma-Separated Strings into Table

and

dbo.Split

astander
Check out http://www.sommarskog.se/arrays-in-sql-2005.html for an analysis of the many possible split functions. Long, but well worth the read.
Tom H.