Concatenating distinct column values in SQL Server

Gerald Baretto picture Gerald Baretto · Aug 29, 2015 · Viewed 7.2k times · Source

I am trying to concatenate many columns and separating it with a comma as below:

Column
------
abc
bcd
bgd
abc

Expected output: abc,bcd,bgd

I am using this code:

CREATE FUNCTION concatinate(@PK uniqueidentifier)
RETURNS varchar(max)
AS 
BEGIN
    DECLARE @result varchar(max)

    SELECT @result = ISNULL(@result + ', ', '') + Column
    FROM table

The result I am getting is

abc,bcd,bgd,abc

I am not able to only select the distinct values. Please guide.

Answer

Yasin picture Yasin · Aug 29, 2015

Suppose your table name is tb then your sql query would be:

SELECT dist.Column  + ','
FROM(
     SELECT DISTINCT t.Column
     FROM dbo.tb t) dist
FOR XML PATH ('')

By this u will get unique values. But at the end you will extra comma ',' you can remove it by string functions. Hope this works