Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oracle NVL中的Select语句_Oracle_Nvl - Fatal编程技术网

Oracle NVL中的Select语句

Oracle NVL中的Select语句,oracle,nvl,Oracle,Nvl,我正在尝试运行以下查询: select a.*, case when NVL (SELECT max(b.field1) FROM b where b.field2 = a.tbl_a_PK , 'TRUE') = 'TRUE' then 'has no data in b' else 'has data in b' end as b_status from a 我进行了检查,nvl中的select只返

我正在尝试运行以下查询:

select a.*, 
    case when NVL (SELECT max(b.field1)
        FROM b
        where b.field2 = a.tbl_a_PK , 'TRUE') = 'TRUE' 
            then 'has no data in b'
            else 'has data in b' end as b_status
from a
我进行了检查,nvl中的select只返回1个值,因此应该没有问题。
但是,如果您在a中搜索在b中有/没有关联记录的记录,我会得到“ORA-00936:缺少表达式”

select a.*, 
       case when b.field2 is null then 'has no data in b'
                                  else 'has data in b'
        as b_status
from a left outer join b
on a.tbl_a_PK = b.field2;

如果要执行此操作,NVLstring1将_替换为需要2个参数的函数,请参阅此处的文档: Ora 10g文档: 因为您知道问题所在,所以此查询可以解决问题:

select a.*,
       case
         when (SELECT NVL(b.field2, 0) FROM b where b.field2 = a.tbl_a_PK and rownum = 1) > 0 then
          'has data in b'
         else
          'has no data in b'
       end b_status
  from a
而且跑得更快。 您不需要max来检查该值是否存在于另一个表中,只需检查主键是否为空。

NVL需要两个参数:要测试的表达式和默认值,例如nvlsome_字段,111。您只需要用大括号分隔查询参数,并提供第二个参数,如以下语句所示:

select nvl( (select 1 from dual), 34) from dual 
在您的变体中,解析器在SELECT关键字后需要逗号,无法解析剩余的字符串

您的声明必须如下所示:

select 
  a.*, 
  case when NVL(
              ( SELECT max(b.field1)
                FROM b
                where b.field2 = a.tbl_a_PK
              ), 
              'TRUE'
            ) = 'TRUE' 
       then 'has no data in b'
       else 'has data in b' end                  as b_status
from a
希望这有助于

更新 就性能而言,最好使用exists而不是max:


刚才我意识到我可以很容易地做到这一点:选择一个*,如果从b中选择maxb.field1,其中b.field2=a.tbl_a_PK为空,那么“b中没有数据”或者“b中有数据”结束,就像a中的b_状态一样。但是我仍然很好奇nvl的问题是什么。您需要在函数中用括号括住select语句。使用联合而不是Nvl是更好的实践
select 
  a.*, 
  case when exists
              ( SELECT null
                FROM b
                where b.field2 = a.tbl_a_PK 
                      and 
                      b.field2 is not null
                      and 
                      rownum = 1
              ), 
       then 'has data in b'
       else 'has no data in b' end                  as b_status
from a