Coalesce 和 nullif 有什么区别

what is the difference between Coalesce and nullif

我目前正在处理一份 SSRS 报告,该报告需要根据 DEA 编号或 NPI 编号显示医生 ID。我需要能够对 DEA 和 NPI 进行合并以找到非未知的,然后我将代码添加到 SSRS 报告中,该报告将显示悬停状态,说明是 "DEA Number" 还是 "NPI Number" 正在显示。

以下 SQL 是否可以在后端完成此操作?从我在网上读到的内容来看,nullif 和 coalesce 似乎非常相似,想知道它们之间的区别是什么,以及它们是否可以一起使用来满足这个要求。

coalesce(nullif(convert(varchar,NationalProviderIdentifier),'0'), DEANumber) as 'Dr Id'

它们或多或少没有关联。

coalesce() 采用 list 值和 returns 第一个 non-null 值(或 null 如果所有值都是 null).

nullif() 采用 两个 值和 returns 第一个值,除了 returns null 如果值相等.


如果将两者转换为case语句,则为:

coalesce:

case
    when value1 is not null then value1
    when value2 is not null then value2
    ... etc
    else null
end

nullif:

case when value1 = value2 then null else value1 end
T coalesce(T a, T b) {
    if(a != null) return a;
    return b;
}
        
T nullif(T a, T b) {
    if(a == b) return null; 
    return a;
}