Convert or split comma separated string into table rows in Sql server

Introduction: In this article I am going to share how to convert or split large comma separated string into table rows using our own created custom function in sql server.


Description: Here I will create a table valued user defined function that splits or converts  a string containing words or letters separated by comma into table rowset. 

Implementation: Let’s create a user defined function to split passed string

CREATE FUNCTION SplitString
(
            @Str NVARCHAR(MAX),
            @Separator     CHAR(1)
)
RETURNS @ResultOutput TABLE(Id INT IDENTITY(1,1), Result NVARCHAR(100))
AS
BEGIN
            DECLARE @Splitted_string NVARCHAR(4000)
            DECLARE @Pos INT
            DECLARE @NextPos INT
           
            SET @Str = @Str + @Separator
            SET @Pos = CHARINDEX(@Separator,@Str)
            WHILE (@pos <> 0)
                        BEGIN
                                    SET @Splitted_string = SUBSTRING(@Str,1,@Pos - 1)
                                    SET @Str = SUBSTRING(@Str,@pos+1,LEN(@Str))
                                    SET @pos = CHARINDEX(@Separator,@Str)
                                    INSERT INTO @ResultOutput VALUES(@Splitted_string)
                        END
            RETURN
END 

You just need to pass the string and the separator e.g. if the string have words or letters separated by comma then pass that string and the separator  ','(Comma) to the function. Similarly if the string contains the words or letters separated by space then pass the separator ' '(space) to split the string into table rows.

Using SplitString function In Query: 

--Split string by comma
SELECT Result FROM SplitString('Split,string,example,in,sql,server',',')

--Split string by pipe symbol
SELECT Result FROM SplitString('Split|string|example|in|sql|server','|')

--Split string by space
SELECT Result FROM SplitString('Split string example in sql server',' '

Query output will be as: 

Result
Split
string
example
In
Sql
server


Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..