Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2008

SQL Server 2008 - Loop through/split a delimited string

2.77/5 (6 votes)
15 Mar 2012CPOL 77.8K  
Loop through/split a delimited string.
SQL
DECLARE @Str NVARCHAR(MAX)
SET @Str = ',Rajesh,Ganpat,Varu,Smith,GANUSHARMA,Vandana,Anil,Rajvir,Feroz,Anup,Manoj,'
DECLARE @Part NVARCHAR(MAX)
DECLARE @IND    INT
SET @IND = CHARINDEX(',',@Str)
DECLARE @EIND INT set @EIND = 0
WHILE(@IND != LEN(@STR))
BEGIN
    SET  @EIND = ISNULL(((CHARINDEX(',', @Str, @IND + 1)) - @IND - 1), 0)
    SELECT (SUBSTRING(@Str, (@IND  + 1),  @EIND))
    SELECT @IND = ISNULL(CHARINDEX(',', @STR, @IND + 1), 0)
END

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)