Remove duplicate values in a cell SQL Server [clos

2019-08-08 06:10发布

How do I remove duplicates in the following case in T-SQL?

I have a table with a column Code of type varchar(max).

It contains a value like A/A/B/C. I need the cell value to be A/B/C.

Other possibility is A/B/C/A need to be A/B/C

Thanks

2条回答
Fickle 薄情
2楼-- · 2019-08-08 06:28

Try this.

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 @tempstr=@tempstr + Substring(@Str, 1, 1)
            SET @Str=Replace(@Str, Substring(@Str, 1, 1), '')
            SELECT @outstr = @outstr + RIGHT(@tempstr, 1) + '/'
            SET @count=@count + 1
        END

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

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

OUTPUT : B/A/C

If you want to remove duplicates and if dont care about the order then try this.

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) 

OUTPUT : A/B/C

查看更多
Deceive 欺骗
3楼-- · 2019-08-08 06:31

I'm using the blow code from this linke [SQL SERVER – Remove Duplicate Entry from Comma Delimited String]http://blog.sqlauthority.com/2009/01/15/sql-server-remove-duplicate-entry-from-comma-delimited-string-udf/)

CREATE FUNCTION dbo.DistinctList
(
    @List VARCHAR(MAX),
    @Delim CHAR
)
RETURNS
    VARCHAR(MAX)
AS
BEGIN
    DECLARE @ParsedList TABLE
    (
    Item VARCHAR(MAX)
    )
    DECLARE @list1 VARCHAR(MAX), @Pos INT, @rList VARCHAR(MAX)
    SET @list = LTRIM(RTRIM(@list)) + @Delim
    SET @pos = CHARINDEX(@delim, @list, 1)
    WHILE @pos > 0
    BEGIN
        SET @list1 = LTRIM(RTRIM(LEFT(@list, @pos - 1)))
        IF @list1 <> ''
        INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX)))
        SET @list = SUBSTRING(@list, @pos+1, LEN(@list))
        SET @pos = CHARINDEX(@delim, @list, 1)
    END
    SELECT @rlist = COALESCE(@rlist+@Delim,'') + item
    FROM (SELECT DISTINCT Item FROM @ParsedList) t
    RETURN @rlist
END
GO

I changed the SELECT @rlist = COALESCE(@rlist+',','') + item to SELECT @rlist = COALESCE(@rlist+@Delim,'') + item because the original code is returning string with comma.

How to use:

SELECT dbo.DistinctList('A/B/C/A/A/A','/') DistinctList
查看更多
登录 后发表回答