1

Is there any alternate way to concatenate SQL columns with comma separated. I am using below logic for concatenation. The columns (col1,col2,col3) can have null values.

select 
stuff(
        left(concat(col1,',',col2,',',col3),
            len(concat(col1,',',col2,',',col3)) -
        patindex('%[^,]%',reverse(concat(col1,',',col2,',',col3)))+1
            )
        ,1,
        patindex('%[^,]%',concat(col1,',',col2,',',col3))-1,''
    )
from mytable
  • Sample data/output

enter image description here

MRR
  • 83
  • 3
  • 9

2 Answers2

5

In more recent versions of SQL Server you can use concat_ws():

select concat_ws(',', col1, col2, col3)

In earlier versions, there are various approach. A pretty simple one is:

select stuff( concat(',' + col1, ',' + col2, ',' + col3), 1, 1, '')
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can concat separators conditionally. This will output an empty string if either of the columns are null or empty.

select concat(col1,
              case when len(col2)>1 then ',' else '' end,
              col2,
              case when len(col3)>1 then ',' else '' end,
              col3) 
from your_table;

To output null if either of the columns are null or empty, wrap the concat inside a nullif like this

select nullif(concat(col1,
              case when len(col2)>1 then ',' else '' end,
              col2,
              case when len(col3)>1 then ',' else '' end,
              col3),'')
from your_table;
Radagast
  • 5,102
  • 3
  • 12
  • 27