Thursday, December 6, 2012

Split Function in Sql Server


Read more about Sql Server Functions here. Below is an example of table-valued split function.

CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))       
returns @temptable TABLE (ID int IDENTITY(1,1),items varchar(8000))    
as    
begin    
    declare @idx int    
    declare @slice varchar(8000)    
   
    select @idx = 1    
        if len(@String)<1 or @String is null  return    
   
    while @idx!= 0    
    begin    
        set @idx = charindex(@Delimiter,@String)    
        if @idx!=0    
            set @slice = left(@String,@idx - 1)    
        else    
            set @slice = @String    
       
        if(len(@slice)>0)
            insert into @temptable(Items) values(@slice)    

        set @String = right(@String,len(@String) - @idx)    
        if len(@String) = 0 break    
    end
return    
end

Execute:
select * from Split('Stmt1,stmmt2',',')


Out put:

ID items
1 Stmt1
2 stmmt2

No comments:
Write comments
Recommended Posts × +