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.
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