Click here to Skip to main content
15,879,535 members
Articles / Database Development / SQL Server / SQL Server 2008
Tip/Trick

SQL Server 2008 - Loop through/split a delimited string

Rate me:
Please Sign up or sign in to vote.
2.77/5 (6 votes)
15 Mar 2012CPOL 76.9K   2   9
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)


Written By
Software Developer Convexicon S/w solution.
India India
Current profile as asp.net & sql developer.

Comments and Discussions

 
QuestionLoop through string and split a delimited string Pin
JERRY_M19-Nov-15 2:17
JERRY_M19-Nov-15 2:17 
SuggestionCan Use this... Pin
Deepak_pandey10-May-13 6:48
Deepak_pandey10-May-13 6:48 
SQL
DECLARE @str VARCHAR(100)
SET @str=',Rajesh,Ganpat,Varu,Smith,GANUSHARMA,Vandana,Anil,Rajvir,Feroz,Anup,Manoj,'
DECLARE @len INT, @lastINDEX INT,@currentINDEX INT
SELECT @len=LEN(@str), @lastINDEX=0,@currentINDEX=0

WHILE @lastINDEX<=@len
BEGIN
SET @currentINDEX=CHARINDEX(',',@str,@lastINDEX)
    IF  @currentINDEX>0
    BEGIN
        PRINT SUBSTRING(@str,@lastINDEX,@currentINDEX-@lastINDEX)
        SET @lastINDEX=@currentINDEX+1
    END
    ELSE
    BEGIN
        PRINT SUBSTRING(@str,@lastINDEX,@len-(@lastINDEX-1))
        SET @lastINDEX=@len+1
    END

END

QuestionOther solution Pin
Gustavo Santis21-Jan-13 14:43
Gustavo Santis21-Jan-13 14:43 
Bugbug Pin
Amiraka11-Sep-12 16:46
Amiraka11-Sep-12 16:46 
GeneralMy vote of 1 Pin
Amiraka11-Sep-12 16:45
Amiraka11-Sep-12 16:45 
Bug[My vote of 1] Problem Pin
Amiraka11-Sep-12 16:44
Amiraka11-Sep-12 16:44 
QuestionProblem Pin
Amiraka11-Sep-12 16:42
Amiraka11-Sep-12 16:42 
AnswerRe: Problem Pin
Me To Mee9-Oct-12 3:48
Me To Mee9-Oct-12 3:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.