Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Supprimer les valeurs en double dans une cellule SQL Server

Essayez ceci.

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')

SORTIE : B/A/C

Si vous souhaitez supprimer les doublons et si vous ne vous souciez pas de la commande, essayez ceci.

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) 

SORTIE :A/B/C