Search This Blog

Sunday, September 25, 2011

SQL way to Splitting Strings to Substrings

There are lot of ways to split strings in sql, here i am mentioning one of the simple way 
using CHARINDEX......
BEGIN
    DECLARE @List varchar(MAX)
    DECLARE @Delimiter nvarchar(10)
    SET @List = 'string 1,string 2, string 3, string 5'
    SET @Delimiter = ','
    DECLARE @LenString int
    SET @List = @List + @Delimiter
    WHILE LEN(@List) > 0
        BEGIN
            SET @LenString = CHARINDEX(@Delimiter, @List) - 1
            SELECT @LenString
            SELECT SUBSTRING(@List, 1, @LenString)
            SET @List = RIGHT(@List, LEN(@List) - @LenString - 1)
        END
    RETURN
END
 
The output will look like as below : 

 

No comments:

Post a Comment