Wednesday, July 28, 2010

SQL Server 2005 - Loop through/split a delimited string
Here is a further cleaned up, generalized, and working version of a T-SQL script to take in comma delimited list and parse it into elements and operate on the individual values:


GO
DECLARE @commaList AS VARCHAR(MAX)
SET @commaList = '1,2,3,4'

DECLARE @pos as INT
IF substring(@commaList, LEN(@commaList),1) <> ','
        SET @commaList = @commaList + ','

print substring(@commaList, LEN(@commaList),1)
SET @pos=0
DECLARE @listItem as int

WHILE charindex(',',@commaList)>0
    BEGIN
        SET @listItem = cast(substring(@commaList,0, charindex(',',@commaList)) as int)
        /***********PERFORM ACTION***********/
        PRINT @listItem
        /*************END ACTION*************/
        SET @commaList = substring(@commaList, charindex(',',@commaList)+1, LEN(@commaList) - @pos) --remove the first item from the list
    END

GO

The original script came from here, but was too specific to the original writer's needs and did not perform any action on the last value...
The original writer also mentions, that he (and I) does the cast to int because he requires an INT. If you do not, do not do the cast.

"SQL Server 2005 - Loop through/split a delimited string"
http://www.vbforums.com/showthread.php?t=507592