1

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?

Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174

1 Answers1

2

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.

mellamokb
  • 56,094
  • 12
  • 110
  • 136