我有以下代码
SELECT @columns = COALESCE(@columns + ', ','') + QUOTENAME(PERIOD)
FROM (SELECT DISTINCT PERIOD FROM @p_l_summary) AS b
ORDER BY b.PERIOD
完美无缺,但会生成一些NULL值。
我知道我需要在@columns周围包装一个ISNULL,但任何人都可以给我正确的语法 - 无论我尝试生成错误还是似乎都没有效果。
答案 0 :(得分:2)
COALESCE
返回第一个非空值,因此它在您的情况下充当ISNULL
。
因此,只有PERIOD列为null时,您的查询才能返回null。您可以过滤掉这些值:
SELECT @columns = COALESCE(@columns + ', ','') + QUOTENAME(PERIOD)
FROM (SELECT DISTINCT PERIOD FROM @p_l_summary WHERE PERIOD IS NOT NULL) AS b
ORDER BY b.PERIOD
或在PERIOD上使用ISNULL
:
SELECT @columns = COALESCE(@columns + ', ','') + ISNULL(QUOTENAME(PERIOD), '')
FROM (SELECT DISTINCT PERIOD FROM @p_l_summary) AS b
ORDER BY b.PERIOD
答案 1 :(得分:1)
添加额外条件怎么样?
WHERE PERIOD IS NOT NULL