對NVL(),Decode()等幾個Oracle函數的猜測

Wayne posted @ Mon, 06 Dec 2010 15:16:29 +0000 in Experience , 2711 readers

今天有個需求,要在存儲過程中取出當天的一些配置進行比較。但是這個配置是每天輸入的,那麼當尚未輸入的時候,這個比較會報出“NO_DATA_FOUND”的錯誤。解決辦法當然也有,在之前做個判斷或者在之後的exception裡進行一些操作都可以。但是兩者都會有更多的語句要寫,讓我很煩躁。我於是想用NVL來實現。

select nvl(replyexpected,'1') from USR_DFW_SCHE where SendDay=trunc(sysdate)

今天的配置已經輸入了,自然這條語句可以正確取出值。為了測試尚未輸入記錄的情況,我將sysdate改成了sysdate+1,也就是:

select nvl(replyexpected,'1') from USR_DFW_SCHE where SendDay=trunc(sysdate+1)

結果返回的不是我預想中的'1',而是什麼也沒有。

採用Decode()函數也一樣:

select decode(replyexpectd,NULL,'1',replyexpected) from USR_DFW_SCHE where SendDay=trunc(sysdate+1)

結果無任何返回。

將語句分解,在當天記錄存在的情況下,select '1' from USR_DFW_SCHE where SendDay=trunc(sysdate) 返回 ‘1’,而 select '1' from USR_DFW_SCHE where SendDay=trunc(sysdate+1) 這樣連滿足條件的記錄都沒有的查詢,則不返回任何結果。

由此,我想大致可以推斷Oracle的NVL()和Decode()函數的內部實現應該是這樣的過程:

 

 select A  from TB_C where cond=D;

 if (A is null) then

    select B into result from TB_C where cond=D;

   return B;

end if;

 

 


Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter