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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With