Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

Concatenate or merge many columns values with a separator between and ignoring nulls - SQL Server 2016 or older

I want to simulate the CONCAT_WS SQL Server 2017+ function with SQL Server 2016 version or older in order to concatenate many columns which values are strings like that:

Input:

| COLUMN1 | COLUMN2 | COLUMN3 | COLUMN4 |
   'A'        'B'       NULL     'D'
   NULL       'E'       'F'      'G'
   NULL       NULL      NULL     NULL

Output:

| MERGE |
 'A|B|D'
 'E|F|G'
  NULL

Notice that the output result is a new column that concatenate all values separated by '|'. The default value should be NULL if there are no values in the columns.

I tried with CONCAT and a CASE statement with many WHEN conditions but is really dirty and I am not allowed to use this solution. Thanks in advance.

question from:https://stackoverflow.com/questions/65924066/concatenate-or-merge-many-columns-values-with-a-separator-between-and-ignoring-n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One convenient way is:

select stuff( coalesce(',' + column1, '') +
              coalesce(',' + column2, '') +
              coalesce(',' + column3, '') +
              coalesce(',' + column4, ''), 1, 1, ''
            )

         

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...