Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating distinct column values in SQL Server

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.

like image 349
Gerald Baretto Avatar asked Aug 29 '15 11:08

Gerald Baretto


People also ask

How do I concatenate data from two columns in SQL?

SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function. This method will change the original table.

Can you concatenate columns in SQL?

In SQL, you can also concatenate numerical data from the table in the same way as we concatenate strings. The CONCAT function can also be used to join numeric values.


2 Answers

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

Using this approach you will get unique values. But at the end you will get an extra comma ','. This can removed by using string helper functions. Hope this helps

like image 161
Yasin Avatar answered Nov 15 '22 05:11

Yasin


A few amendments to your original code:

DECLARE @result varchar(max)

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

PRINT(@result)

This will concatenate a distinct list. Unlike the initial answer above, you will not get an extra comma ',' at the end.

like image 33
Monaheng Ramochele Avatar answered Nov 15 '22 04:11

Monaheng Ramochele