SQL 仅当列不为空时才用逗号分隔服务器串联

SQL Server concatenation separated by comma only when column is not null

我有以下 SQL 声明:

@All = COALESCE(NULLIF(@Asc1, '') + ',', '') +
        OALESCE(NULLIF(@Asc2, '') + ',', '') +
        OALESCE(NULLIF(@Asc3, '') + ',', '');

即使任何变量(@Asc1@Asc2@Asc3)具有 NULL 或空值,这也会在末尾插入一个逗号。

例如:

我希望 @All 成为 1234,3456

谢谢。

使用 stuff() 删除第一个逗号并反转逗号连接:

set @all = stuff(
    coalesce(','+nullif(@Asc1, ''), '')
  + coalesce(','+nullif(@Asc2, ''), '')
  + coalesce(','+nullif(@Asc3, ''), '')
  ,1,1,'');

rextester 演示:http://rextester.com/UNDS90887

returns: 1234,3456

我知道这个 post 已经回答并且是正确的。但是想要 post 下面的答案,因为从 SQL Server 2017 开始,这太简单了,将来可能会有人觉得这很有用。

SELECT @all = CONCAT_WS(',',@Asc1,@Asc2,@Asc3)