为什么NVL2在不期望时会返回NULL?

时间:2014-11-27 05:07:39

标签: sql oracle

让准备结构

create table RESOURCE1(id number, valueA varchar2(255));
create table RESOURCE2(id number, valueB varchar2(255));
create table IDS(id number);

insert into IDS
  select 1 from DUAL
  union select 2 from DUAL
  union select 3 from DUAL
  union select 4 from DUAL;

insert into RESOURCE1
      select 1, 'ABC' from dual
union select 2, 'DEF' from dual;

insert into RESOURCE2
      select 3, 'GHI' from dual
union select 4, 'JKL' from dual;

以下查询

select P.VALUEA, Q.VALUEB
     , NVL2(P.VALUEA, Q.VALUEB, P.VALUEA) FROM_NVL2 
     , case when P.VALUEA is null then Q.VALUEB else P.VALUEA end FROM_CASE
  from IDS
  left join RESOURCE1 P on P.ID = IDS.ID
  left join RESOURCE2 Q on Q.ID = IDS.ID
    order by ids.id;

生成

VALUEA  VALUEB  FROM_NVL2   FROM_CASE
 ABC    (null)    (null)       ABC
 DEF    (null)    (null)       DEF
(null)   GHI      (null)       GHI
(null)   JKL      (null)       JKL

为什么FROM_NVL2列包含所有空值?我一直期望FROM_NVL2会产生与FROM_CASE相同的值。

2 个答案:

答案 0 :(得分:2)

NVL2()的逻辑是described

  

NVL2允许您根据是否确定查询返回的值   指定的表达式为null或不为null。如果expr1不为null,那么   NVL2返回expr2。如果expr1为null,则NVL2返回expr3。

等效case将是:

(case when P.VALUEA is not null then Q.VALUEB else P.VALUEA end)

答案 1 :(得分:1)

从您的case示例中,您似乎尝试使用NVL2作为空值合并3个值的方法,或者您已经交换了订单expr2expr3 ,这是不正确的。

相当于case when P.VALUEA is null then Q.VALUEB else P.VALUEA end

NVL2(P.VALUEA, P.VALUEA, Q.VALUEB)

与基本NVL相同:

NVL(P.VALUEA, Q.VALUEB)