Sunday 11 March 2012

Split Function in Sql Server to break Comma-Separated Strings into Table

Sql Server does not (on my knowledge) have in-build Split function.
Split function in general on all platforms would have comma-separated string value to be split into individual strings.
In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
  1. CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
  2. returns @temptable TABLE (items varchar(8000))       
  3. as       
  4. begin       
  5.     declare @idx int       
  6.     declare @slice varchar(8000)       
  7.       
  8.     select @idx = 1       
  9.         if len(@String)<1 or @String is null  return       
  10.       
  11.     while @idx!= 0       
  12.     begin       
  13.         set @idx = charindex(@Delimiter,@String)       
  14.         if @idx!=0       
  15.             set @slice = left(@String,@idx - 1)       
  16.         else       
  17.             set @slice = @String       
  18.           
  19.         if(len(@slice)>0)  
  20.             insert into @temptable(Items) values(@slice)       
  21.   
  22.         set @String = right(@String,len(@String) - @idx)       
  23.         if len(@String) = 0 break       
  24.     end   
  25. return       
  26. end  
split function can be Used as
  1. select top 10 * from dbo.split('hello,world,!',',')  
would return
hello
world
!

Above Split function can be used to pass parameter to IN clause in sql server.

No comments:

Post a Comment