SIGN UP MEMBER LOGIN:    
Blog

Split Comma-Separated Strings into Sql Server

Posted by Manish Dwivedi Blogs | SQL Server 2012 Oct 05, 2011
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

CREATE FUNCTION dbo.SplitString(@StringValue varchar(2000), @Delimiter char(1))    

returns @resulttable TABLE (words varchar(2000))    

as    

begin    

      declare @index int    

      declare @sliceOfStringValue varchar(2000)    

   

      set @index = 1    

            if len(@StringValue)<1 or @StringValue is null  return    

   

      while @index!= 0    

      begin    

            set @index = charindex(@Delimiter,@StringValue)    

            if @index!=0    

                  set @sliceOfStringValue = left(@StringValue,@index - 1)    

            else    

                  set @sliceOfStringValue = @StringValue    

           

            if(len(@sliceOfStringValue)>0)

                  insert into @resulttable(words) values(@sliceOfStringValue)    

 

            set @StringValue = right(@StringValue,len(@StringValue) - @index)    

            if len(@StringValue) = 0 break    

      end

return    

end

 

share this blog :
post comment