在NVL中选择语句

时间:2013-05-22 15:37:03

标签: 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只返回1个值(所以那里应该没有问题)。 但是我得到'ORA-00936:缺少表达'

3 个答案:

答案 0 :(得分:4)

NVL()需要2个参数:要测试的表达式和默认值,例如nvl(some_field, 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

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

答案 1 :(得分:1)

如果您正在搜索b中有/没有关联记录的记录

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;

应该这样做

答案 2 :(得分:1)

NVL(string1,replace_with)函数需要2个参数,请参阅此处的文档: http://www.techonthenet.com/oracle/functions/nvl.php
Ora 10g docs:http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions105.htm
由于您知道该问题,因此该查询可以解决该问题:

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()来检查该值是否存在于另一个表中,只需检查主键是否为空。