devxlogo

Remove Duplicates from Delimited String in T-SQL

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 @CachedString=@CachedString + @myword + ' '    end   SELECT @j = @i   select @i = CHARINDEX (' ' , @mystring, @i + 1)ENDprint left(@CachedString,len(@CachedString)-1)
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist