Chitika

Sunday, January 20, 2013

Split String in SQL Server

How to split a string based on the delimiter(any character), this is the requirement we get when we are working with sql server.
In this article i am going to show you, how to that.

 Apart from split the string , i am showing how many records(Rows) we get by using RowID.
 I am writing one User Defined Function, because we can use it any where.


GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitString](@String varchar(8000), @Delimiter char(1))      
returns @temptable TABLE (items varchar(8000),RowId INT)      
as      
begin      
    declare @idx int      
    declare @slice varchar(8000)      
    DECLARE @RowID INT
    set @RowID=0
    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)
        set @RowID= @RowID+1
            insert into @temptable(Items,RowId) values(@slice,@RowID)      
 
        set @String = right(@String,len(@String) - @idx)      
        if len(@String) = 0 break      
    end  
return      
end


Now you can use the select statement to test it, by passing
string =Asp.net,C#,sql
 Delimiter=,(Comma)

SELECT  items,Rowid FROM dbo.SplitString('Asp.net,C#,sql',',') 
By using this statement you will get all.

If you want specific part from the string use where condition, as
SELECT  items, Rowid FROM dbo.SplitString('Asp.net,C#,sql',',')  where rowid=3

Happy Programming,,,,,,,




No comments:

Post a Comment