title: SQL: How can I replace duplicate characters in a column?
body: <p>I have a column called "Mergecodes" that contains characters(or pairs) separated by commas. Some of the entries contain multiples that need to be removed. Here is an example where 'KD' is a duplicate and therefore one needs to be removed:  "<strong>T, M, KD, SB, KD</strong>".  I imagine this would work by counting the number of occurrences and if it contains more than one, delete the extras. I'm just not sure about the syntax for this. Any help would be greatly appreciated. Thanks!</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I was able to get results when using a string('T,M,KD,SB,KD') as @Yaroslav suggested, but when I use the column instead of the string I get no results. Any ideas?</p>
  
  <pre><code>declare @str varchar(100)
  select @str = mergecodes from GoldMineTest.dbo.CONTACT1
  declare  @separator varchar(1)= ','
  
  ;WITH tokens(p, a, b) AS
          (
              SELECT 1, 1, CHARINDEX(@separator, @str)
               UNION ALL
              SELECT p + 1, b + 1, CHARINDEX(@separator, @str, b + 1)
                FROM tokens
               WHERE b &gt; 0
          )
  SELECT SUBSTRING(@str, a, CASE WHEN b &gt; 0 THEN b-a ELSE 4000 END) AS Separated_values, count(SUBSTRING(@str, a, CASE WHEN b &gt; 0 THEN b-a ELSE 4000 END))
    FROM tokens
   GROUP BY SUBSTRING(@str, a, CASE WHEN b &gt; 0 THEN b-a ELSE 4000 END)
  HAVING count(SUBSTRING(@str, a, CASE WHEN b &gt; 0 THEN b-a ELSE 4000 END))=1
  </code></pre>