0

有没有其他方法可以用逗号分隔连接 SQL 列。我正在使用以下逻辑进行连接。列 (col1,col2,col3) 可以有空

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
  • 样本数据/输出

在此处输入图像描述

4

2 回答 2

2

在较新版本的 SQL Server 中,您可以使用concat_ws()

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

在早期版本中,有多种方法。一个非常简单的方法是:

select stuff( concat(',' + col1, ',' + col2, ',' + col3), 1, 1, '')
于 2021-06-21T11:10:10.260 回答
0

您可以concat有条件地分隔。如果任一列为空或为空,这将输出一个空字符串。

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

如果任一列为 null 或为空,要输出 null,请像这样将concat内部包装起来nullif

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;
于 2021-06-21T15:18:43.240 回答