2

For circumstances out of my hand, I have a string of values:

@param1 = "1,2,3,4";

How do I do IN statement to check if an ID is in my string @param1?

so, it would look something like this:

select * from table1 where ID IN (@param1);

Normally, I guess I should have this:

select * from table1 where ID IN (1,2,3,4);

But unfortunately, under my circumstances, I simply don't have that, instead, I have just one parameter of type string of all my IDs concatenated, how do I select the rows from that?

1

1 Answer 1

3

You can use a dynamically-generated SQL statement (DEMO):

declare @sql varchar(max)

set @sql = 'select * from table1 where ID IN (' + @param1 + ')'
exec(@sql)

The idea is to build a SQL statement in a string variable by concatenating the ID list into a SQL statement. The final statement looks like your expected query:

select * from table1 where ID IN (1,2,3,4)

Then you can run the contents of the string variable as a SQL command using exec.

Sign up to request clarification or add additional context in comments.

1 Comment

My query is really really long... is there anyway you can separate the @param1 dynamic query into it's own query?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.