用逗号分隔连接 SQL 列

时间:2021-06-21 11:07:36

标签: sql sql-server tsql string-aggregation stuff

是否有其他方法可以用逗号分隔连接 SQL 列。我使用以下逻辑进行连接。列 (col1,col2,col3) 可以有 null 值。

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
  • 示例数据/输出

enter image description here

2 个答案:

答案 0 :(得分:2)

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

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

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

select stuff( concat(',' + col1, ',' + col2, ',' + col3), 1, 1, '')

答案 1 :(得分: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;