Share via

Remove duplicate values from the same cell

Sweta 96 Reputation points
2021-01-08T16:12:34.807+00:00

Hi All,

If in one cell I have a value like - text1, text1, text2, text2, text3

How do I get it to text1, text2, text3 please

thanks in advance

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Sweta 96 Reputation points
2021-01-08T16:17:01.437+00:00

I found this function and it gave me what I needed.

Create FUNCTION dbo.RemoveDuplicate
(
@StringList 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 @StringList = LTRIM(RTRIM(@StringList)) + @Delim
SET @POS = CHARINDEX(@delim, @StringList, 1)
WHILE @POS > 0
BEGIN
SET @list1 = LTRIM(RTRIM(LEFT(@StringList, @POS - 1)))
IF @list1 <> ''
INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX)))
SET @StringList = SUBSTRING(@StringList, @POS +1, LEN(@StringList))
SET @POS = CHARINDEX(@delim, @StringList, 1)
END
SELECT @rlist = COALESCE(@rlist+@Delim,'') + item
FROM (SELECT DISTINCT Item FROM @ParsedList) t
RETURN @rlist
END
GO

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 126.9K Reputation points
    2021-01-08T16:19:56.237+00:00

    In the future you can also try something like this too:

    select *,
        (
            select string_agg(value, ', ') within group (order by value) d
            from (select distinct trim(value) as value from string_split( MyColumn, ',')) d
        )
    from MyTable
    

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.