SQL Server does not have a straight forward way to do a For Loop with a list of string values.
The easiest solution I found, can be seen below:
DECLARE @list varchar(8000) DECLARE @pos INT DECLARE @len INT DECLARE @value varchar(8000) SET @list = 'A101,A203,B12341,C124,' set @pos = 0 set @len = 0 WHILE CHARINDEX(',', @list, @pos+1)>0 BEGIN set @len = CHARINDEX(',', @list, @pos+1) - @pos set @value = SUBSTRING(@list, @pos, @len) PRINT @value -- for debug porpose --DO YOUR MAGIC HERE set @pos = CHARINDEX(',', @list, @pos+@len) +1 END
Please check the original website: https://www.admfactory.com/split-a-string-and-loop-in-sql-server/
The easiest solution I found, can be seen below:
DECLARE @list varchar(8000) DECLARE @pos INT DECLARE @len INT DECLARE @value varchar(8000) SET @list = 'A101,A203,B12341,C124,' set @pos = 0 set @len = 0 WHILE CHARINDEX(',', @list, @pos+1)>0 BEGIN set @len = CHARINDEX(',', @list, @pos+1) - @pos set @value = SUBSTRING(@list, @pos, @len) PRINT @value -- for debug porpose --DO YOUR MAGIC HERE set @pos = CHARINDEX(',', @list, @pos+@len) +1 END
Please check the original website: https://www.admfactory.com/split-a-string-and-loop-in-sql-server/
Comments
Post a Comment