Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I want to use In cause with dynamic variable,

Example :

declare @MultipleCategory nvarchar(20)
set @MultipleCategory ='2,3'

select video.videoid from video join category on videoid=category.videoid
WHERE category.CategoryID IN (@MultipleCategory)

but it is not working.

I know i can use dynamic SQL but it will competitive, if we have large query.
Posted

The short answer is: You can't.

But there are plenty of workarounds. Erland Sommarskog[^] to the rescue.
 
Share this answer
 
First, it is a clause, not cause ^_^

Second, the "in" clause works off of a set of inputs, that is a table like structure with one column. What you have in your "in" clause is one item. A varchar.

If it was written like this:
SQL
WHERE category.CategoryID IN (2,3)

That would work. You have:
SQL
WHERE category.CategoryID IN ('2,3') which won't even match by type.


If you must use a csv to pass in your list, then you will need to convert it into a table column. You can use a csv parser Table Valued Function for this. Many examples exist and I will link one at the bottom.

This can be used as follows:

SQL
WHERE category.CategoryID IN ([dbo].[GetMyTable](@MultipleCategory))


here is the link:
SQL function to return CSV as a table[^]

The function steps through the string one char at a time so it quite scaleable
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900