简体   繁体   中英

Concatenate multiple column names into 1 column SQL

I am struggling with small problem here. I have a table with 4 columns

Column1 | Column2 | Column3 | Column4
NULL.........NULL.........NULL.........NULL
ABC..........NULL..........XYZ...........NULL


Column 1,2 & 3 may have some value or null, column4 is null
When any of the column1,2 or 3 are not null, I have to update column4 with that column name. I am expecting following result

Column1 | Column2 | Column3 | Column4
NULL.........NULL.........NULL.........NULL
ABC..........NULL..........XYZ...........Column1,Column3


Can anyone guide me how can I achieve this result.
Any help is appreciated. Thanks in advance.

Use a case to test for null values and return the column name when it is not null. The stuff is there to remove the extra comma you get first in the string.

update YourTable 
set Column4 = stuff(case when Column1 is not null then ',Column1' else '' end +
                    case when Column2 is not null then ',Column2' else '' end +
                    case when Column3 is not null then ',Column3' else '' end, 1, 1, '')

SQL Fiddle

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