Remove Duplicates from Delimited String in T-SQL

Use this snippet to remove duplicates from a delimited string:

 DECLARE @mystring varchar(1000), @myword varchar(50),@CachedStringvarchar(2000)set @CachedString=''DECLARE @i int,@j intSELECT @mystring = 'cat dog fox cat chicken hen goose cat bird dog'SELECT @i = 0,@j = 0IF SUBSTRING (@mystring, LEN (@mystring), 1) <> ' 'BEGIN   SELECT @mystring = @mystring + ' 'ENDSELECT @i = CHARINDEX (' ', @mystring, @i + 1)WHILE @i > 0BEGIN   SELECT @myword = SUBSTRING (@mystring, @j+1, (@i - @j) -1)   if charindex(@myword,@CachedString)=0    begin    set @[email protected] + @myword + ' '    end   SELECT @j = @i   select @i = CHARINDEX (' ' , @mystring, @i + 1)ENDprint left(@CachedString,len(@CachedString)-1)
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: