2017-03-17 89 views
0
CREATE OR REPLACE FUNCTION func 
RETURN varchar2 AS 
myvar INT; 
BEGIN 
    select 1 into myvar from dual where 1=2; 
    IF myvar IS NULL THEN 
    return 'n'; 
    ELSE 
    return 'y'; 
    END IF; 
END; 


SELECT func() FROM DUAL; 

爲什麼此函數返回NULL而不是字符串「n」,則檢查變量爲空?如果條件爲

+1

因爲you're得到一個異常的'no_data_found'('插入into'這裏不會得到任何數據,這將引發異常),並就好像沒有發生回報=>'null'作爲回報 – SomeJavaGuy

+1

SomeJavaGuy搞定了。 PL/SQL中的SELECT ... INTO ...語句必須返回一行,否則會引發異常:如果不返回行,則返回「NO_DATA_FOUND」,返回兩行或多行則返回「TOO_MANY_ROWS」。 –

回答

2

因爲you're變得異常爲no_data_foundinsert into這裏不會得到任何數據,這將引發異常),並就好像沒有發生回報=>null作爲回報:

CREATE OR REPLACE FUNCTION func 
RETURN varchar2 AS 
myvar INT; 
BEGIN 
    select 1 into myvar from dual where 1=2; 
    IF myvar IS NULL THEN 
    return 'n'; 
    ELSE 
    return 'y'; 
    END IF; 
-- This will execute now 
exception 
    when no_data_found then 
     return 'no_data_found'; 
    -- Just to note, when it has 2 rows+ that´s the other possible exception here 
    when to_many_rows then 
     return 'to_many_rows'; 
END; 
/
SELECT func() FROM DUAL; 

O/P

no_data_found