2015-04-22 31 views
5

是否有可能從oracle函數返回null?oracle函數中的可爲空返回類型

我有以下Oracle功能:

create or replace function vta.GetAmount(p_month NUMBER) 
    return number is 
    v_amount number(9); 
begin 
    select amount 
    into v_amount 
    from salary 
    where salary.month = p_month; 
    return v_amount; 
end GetAmount; 

當select語句返回零行,它會引發以下異常: ora-01403: no data found

在這種情況下,我希望函數返回null。

+0

你的SELECT語句返回超過1行對於該代碼失敗,不是因爲它返回0行。如果它將返回0行,您將返回null。 – anudeepks

+0

不,如果它返回了0行,那麼你會得到no_data_found異常。 – Boneist

+0

嘗試從工資 運行僅此, 選擇量 其中salary.month = : 和看到的結果; – anudeepks

回答

4
create or replace function vta.GetAmount(p_month NUMBER) 
    return number is 
    v_amount number(9); 
begin 
    select amount 
    into v_amount 
    from salary 
    where salary.month = p_month; 
    return v_amount; 
    exception -- code to handle no data 
    when no_data_found then 
    return null; 
    end GetAmount; 
0

如果你真的知道/想回到總是一排,你可以改變你的選擇select nvl(sum(amount),0)

  1. sum確保您始終獲得第1行,因爲你沒有分組
  2. nvl如果沒有找到

要知道,你會得到與0取代null當然,如果有多個匹配行,則爲所有匹配行的總和。

3

當您在PL/SQL中執行非批量隱式遊標時(這是您使用SELECT ... INTO ...完成的操作),您必須記住它至少需要1行和至多1行。

如果你得到的行少於或多於1行,你將會得到一個異常 - NO_DATA_FOUND或TOO_MANY_ROWS,這兩者都是不言而喻的。

如果您希望代碼在發生任何異常時執行某些操作,那麼您將需要處理這些異常。

如:

create or replace function vta.GetAmount(p_month NUMBER) 
    return number is 
    v_amount number(9); 
begin 
    select amount 
    into v_amount 
    from salary 
    where salary.month = p_month; 
    return v_amount; 
exception 
    when no_data_found then 
    return null; 
    when too_many_rows then 
    return null; 
end GetAmount;