SQL Server - 没有返回时的COALESCE,获取默认值

时间:2017-08-01 09:28:13

标签: sql sql-server

我正在尝试在SQL Server中使用Coalesce函数来连接多个名称。但是当查询中的条件没有返回任何行或什么都没有时,我需要返回一个默认值。我尝试了一些使用case语句的条件,但我无法弄清楚我错过了什么。

declare @Names varchar(max) = '',
        @Key varchar(max) = 'ABC' 

select @Names = COALESCE(@Names, '') + isnull(T0.A, @Key) + ', ' 
from TData P
left join TNames T0 on T0.C + '\' + T0.D = P.@Key
where OBID=581464 
and ID < 1432081

select @Names

1 个答案:

答案 0 :(得分:1)

您可以对当前代码进行2次微小更改,但我怀疑这是XYProblem,您可能会从编辑问题中获益,包括样本数据和所需结果(因此我们可能会建议一个更好的解决方案)。

无论如何,我想到的是:

declare @Names varchar(max), -- remove the = '', so that @Names starts as null
        @Key varchar(max) = 'ABC' 

select @Names = COALESCE(@Names, '') + isnull(T0.A, @Key) + ', ' 
from TData P
left join TNames T0 on T0.C + '\' + T0.D = P.@Key -- ' (This is just to fix the coding colors)
where OBID=581464 
and ID < 1432081

select COALESCE(@Names, 'default value') -- since @Names started as null, and the query did not return any results, it's still null...
相关问题