Comma separated list in SQL

Go To StackoverFlow.com

26

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.

2012-04-05 15:38
by Virus
Do you want to call the stored procedure for EACH ID seperately? What language are you working outside of SQL - n8wrl 2012-04-05 15:40
If you can't alter the stored, why not call it multiple times - Soader03 2012-04-05 15:40
What version of SQL Server - Yuck 2012-04-05 15:41
SQL Server 2008-yes I want to call the stored procedure for each id as I cannot alter the SP itself. I have execute the SQL query. There is no other language used - Virus 2012-04-05 15:46
+1 for "Give me some ideas, I can carry on from there. - HLGEM 2012-04-05 17:42


70

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

2012-04-05 15:48
by Mikael Eriksson
That is quick! thank you - Virus 2012-04-05 15:52
+1 for the link. Bookmarked : - Ash Burlaczenko 2012-04-05 15:52
+1 for link. Very coo - brian 2012-04-05 17:44
Saved My day.Thanks.. - grv_9098 2013-06-24 11:33
This is perfect! Thanks - NoName 2015-03-12 15:23
This is exactly what I was looking for, thank you so much - user752746 2017-06-28 18:02
Ads