Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated list in SQL

How to loop through comma separated list in SQL? I have a list of ID's and I need to pass these ID's to a stored procedure. I CANNOT alter the stored procedure. I need to figure out how to execute the SP for each id. Give me some ideas, I can carry on from there.

Thanks.

like image 665
Virus Avatar asked Apr 05 '12 15:04

Virus


People also ask

How do I create a comma delimited list in SQL?

Many a times need arises to create comma delimited list in SQL Server. This can be done using the DOR XML PATH feature of SQL Server. The FOR XML PATH generates a xml when used with select statement.

How do I get comma separated values in SQL?

To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.


1 Answers

declare @S varchar(20) set @S = '1,2,3,4,5'  while len(@S) > 0 begin   --print left(@S, charindex(',', @S+',')-1)   exec YourSP left(@S, charindex(',', @S+',')-1)   set @S = stuff(@S, 1, charindex(',', @S+','), '') end 

Try on SE Data: Walk the string

like image 107
Mikael Eriksson Avatar answered Oct 07 '22 00:10

Mikael Eriksson