Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Remover valores duplicados em uma célula SQL Server


Tente isso.
CREATE FUNCTION STR_Func (@Str AS VARCHAR(100))
RETURNS VARCHAR(Max)
AS
  BEGIN
      DECLARE @count   INT,
              @tempstr VARCHAR(100)='',
              @nLength INT,
              @outstr  VARCHAR(100)=''

      SET @count=1
      SET @Str = Replace(@Str, '/', '')
      SET @nlength = Len(@Str)

      WHILE ( @count < @nLength )
        BEGIN
            SET @[email protected] + Substring(@Str, 1, 1)
            SET @Str=Replace(@Str, Substring(@Str, 1, 1), '')
            SELECT @outstr = @outstr + RIGHT(@tempstr, 1) + '/'
            SET @[email protected] + 1
        END

      RETURN LEFT(@outstr, Len(@outstr) - 1)
  END 

select dbo.STR_Func('B/A/C/A')

SAÍDA: B/A/C

Se você deseja remover duplicatas e se não se importa com o pedido, tente isso.
DECLARE @code  VARCHAR(100)='B/A/C/A',
        @code1 VARCHAR(100)=''


SELECT @code1 += '/' + splitrow
FROM   (SELECT DISTINCT Split.a.value('.', 'VARCHAR(100)') splitrow
        FROM   (SELECT Cast ('<M>' + Replace(@code, '/', '</M><M>') + '</M>' AS XML) AS Data) AS A
               CROSS APPLY Data.nodes ('/M') AS Split(a)) b

SELECT RIGHT(@code1, Len(@code1) - 1) 

SAÍDA :A/B/C