Remove duplicate characters from a string in Sqlserver.

Hi all, in this post we will try to remove duplicate characters from the given string.

Logic: First of all we insert each character of string into a temporary table using master..spt_values table. And then we remove duplicate occurrence of the characters.

DECLARE @str nvarchar(100),@result nvarchar(100)

SET @str = ‘taarssysarrrtyr’

SET @result = ”

SELECT substring(@str,number,1) as characters,number into #temp from master..spt_values where type=’p’ and number BETWEEN 1 and LEN(@str)

delete FROM #temp WHERE number NOT IN (SELECT MIN(number) from #temp GROUP BY characters)

SELECT @result=@result+characters FROM #temp

SELECT @result

drop TABLE #temp

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s