31 August 2013

How to Split large string separated by comma in Sql Server

Introduction: In this article I am going to explain how to split a large string into individual strings separated by comma in Sql server.In the Query window of the Sql Server write the following command.

      DECLARE @Splitted_strings NVARCHAR(4000)
      DECLARE @Pos INT
      DECLARE @NextPos INT
      DECLARE @Str NVARCHAR(4000)
      DECLARE @Delimiter NVARCHAR(1)
      SET @Str ='split,string,separated,by,comma,example,in,sql,server,on,webcodeexpert,.com'
      SET @Delimiter = ','
      SET @Str = @Str + @Delimiter
      SET @Pos = charindex(@Delimiter,@Str)
      WHILE (@pos <> 0)
      BEGIN
      SET @Splitted_strings = substring(@Str,1,@Pos - 1)
      SELECT @Splitted_string -- Show Results
      SET @Str = substring(@Str,@pos+1,len(@Str))
      SET @pos = charindex(@Delimiter,@Str)
      print @Splitted_strings  --print Results
      END
Result will be as:
Split
String
Separated
By
Comma
Example
In
Sql
Server
On
Webcodeexpert
.com

No comments:

Post a Comment