简体   繁体   中英

Concatenate several columns as comma-separated string

The following is a starting point to concatenate several columns to one string where the values are comma separated. If the column entry is empty or NULL no comma should be used:

IF OBJECT_ID(N'tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp;

CREATE TABLE #Temp
    (
        Id INT,
        Name1 NVARCHAR(10) ,
        Name2 NVARCHAR(10) ,
        Name3 NVARCHAR(10)
    );

INSERT  INTO #Temp
        SELECT  1,
                N'Name1' ,
                NULL ,
                N'Name3'
UNION
        SELECT  2,
                N'Name1' ,
                N'Name2' ,
                N'Name3'
UNION 
        SELECT  3,
                NULL ,
                NULL ,
                N'Name3'
UNION 
        SELECT  
                4,
                N'' ,
                N'' ,
                N'Name3';

SELECT  Id, STUFF(COALESCE(N',' + Name1, N'') + COALESCE(N',' + Name2, N'')
              + COALESCE(N',' + Name3, N''), 1, 1, '') AS ConcateStuff
FROM    #Temp;

The current results are as follows:

Id  ConcateStuff
1   Name1,Name3
2   Name1,Name2,Name3
3   Name3
4   ,,Name3

Everything work fine for NULL entries but not for empty entries. The last row's result should just be:

Name3

Is there a simple way to get this to work without using complex nested case statements (ultimately I have to concatenate more than 3 columns).

By using NULLIF you can achieve it.

SELECT  Id, STUFF(COALESCE(N',' + NULLIF(Name1, ''), N'') + COALESCE(N',' + NULLIF(Name2, ''), N'')
              + COALESCE(N',' + NULLIF(Name3, ''), N''), 1, 1, '') AS ConcateStuff
FROM    #Temp;

Result

Id  ConcateStuff
-----------------
1   Name1,Name3
2   Name1,Name2,Name3
3   Name3
4   Name3

SQL2012 :

STUFF(CONCAT(',' + Name1, ',' + Name2, ',' + Name3), 1, 1, '')
STUFF(CONCAT(',' + NULLIF(Name1,''), ',' + NULLIF(Name2,''), ',' + NULLIF(Name3,'')), 1, 1, '')

SQL2005+ :

STUFF(ISNULL(','+Name1) + ISNULL(','+Name2) + ISNULL(','+Name2) , 1, 1, '')
STUFF(ISNULL(','+NULLIF(Name1,'')) + ISNULL(','+NULLIF(Name2,'')) + ISNULL(','+NULLIF(Name1,'')) , 1, 1, '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM