內NVL

2013-05-22 27 views
2

我試圖運行下面的查詢Select語句:內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只返回1個值內選擇(所以應該不會有問題那裏)。 但是我得到「ORA-00936:缺少表達式」

+0

剛纔我意識到我可以輕鬆做到這一點:選擇一個*,case when(SELECT max(b.field1) FROM b where b.field2 = a.tbl_a_PK)爲null,則'b'中沒有數據'else'b'中的數據結束爲a中的b_status。但我仍然對nvl的問題感到好奇。 –

+0

您需要在函數內包裝select語句的圓括號。最好使用Coalesce()而不是Nvl() –

回答

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; 

應該這樣做

1

的NVL(STRING1,replace_with)函數需要2個參數,在這裏看到的文檔: http://www.techonthenet.com/oracle/functions/nvl.php
奧拉10克文檔: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()來檢查值是否存在於另一個表中,只需檢查主鍵是否爲空。

1

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