How to Split large comma separated string into table in Sql Server

Introduction:  In this article I am going to explain how to convert a comma separated string into table rows in Sql server.

In previous articles i explained How to Convert column values to comma separated list in sql server and Multiple queries to get all dates between two dates and create database script and Create database from that script and Examples to use CASE Expression in SELECT statement in SQL Server

In the Query window of the Sql Server write the following command.


      DECLARE @Splitted_string NVARCHAR(4000)
      DECLARE @Pos INT
      DECLARE @NextPos INT
      DECLARE @Str NVARCHAR(4000)
      DECLARE @Delimiter NVARCHAR(1)
      DECLARE @Temp TABLE(Result NVARCHAR(100))

      SET @Str ='split,string,separated,by,comma,example,in,sql,server'
      SET @Delimiter = ','
      SET @Str = @Str + @Delimiter
      SET @Pos = CHARINDEX(@Delimiter,@Str)
      WHILE (@pos <> 0)
      BEGIN
                          SET @Splitted_string = SUBSTRING(@Str,1,@Pos - 1)              
                          SET @Str = SUBSTRING(@Str,@pos+1,LEN(@Str))
                          SET @pos = CHARINDEX(@Delimiter,@Str)      
                          INSERT INTO @Temp VALUES(@Splitted_string)
      END
     
      SELECT * FROM @Temp

Result will be as:

Result
split
string
separated
by
comma
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..