Saturday, August 25, 2012

Get Distinct String using SQL Server

Get distinct string between given two string

ALTER function [dbo].[GetDistinctString](@string1 varchar(max),@string2 varchar(max))
returns varchar(max)
as
begin
Set @string2 = ',' + @string2 + ','
Declare @count int,@index int,@s1Len int,@nextIndex int
Set @index=0
Set @nextIndex =1
Set @s1Len=len(@string1)
Declare @part varchar(4)

While(len(@string2)>0 and @index <= @s1Len and @nextIndex <> 0)
begin
    Set @nextIndex = charindex(',',@string1,@index)
    if @nextIndex !=0
    begin
        Set @part = substring(@string1,@index,@nextIndex - @index )
       
    end
    else
    begin
        Set @part = substring(@string1,@index,@s1Len - @index + 1)
       
    end
    --Set @string2 = replace(@string2,@part,'')
    Set @string2 = replace(@string2,','+@part+',',',')
   
    Set @index =@nextIndex+1

end
Set @string1 = @string1 + @string2
Set @s1Len =len(@string1)
return substring(@string1,0,@s1Len)

end

No comments: