我正在尝试使用SQL Server中的Coalesce函数来连接多个名称。但是当查询中的条件不返回行或什么都不返回时,我需要返回默认值。我使用案例陈述尝试了一些条件,但我无法弄清楚我错过了什么。
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
您可以通过对当前代码进行 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...