Function does not return what I am expecting
In my function below开发者_开发知识库 I am trying to understand why it only returns BLAH if I pass in 01356666 and then a null value for anything else passed in. My expectation was that it would return BLAH regardless of what was passed in since I reset the str_mgrin_out after I do the SELECT INTO. I have been testing this in Oracle 10g.
CREATE OR REPLACE FUNCTION GET_MANAGERGIN2 (str_empgin_in IN varchar2)
RETURN varchar2
AS
str_mgrgin_out varchar2(10);
BEGIN
SELECT 'FOO' INTO str_mgrgin_out FROM dual WHERE str_empgin_in = '01356666';
str_mgrgin_out := 'BLAH';
RETURN str_mgrgin_out;
END GET_MANAGERGIN2;
/
-- Returns null but expecting BLAH
SELECT GET_MANAGERGIN2('00356666') FROM dual;
-- Returns BLAH
SELECT GET_MANAGERGIN2('01356666') FROM dual;
I'd assume that this is because if the SELECT INTO
doesn't return exactly one value into str_mgrgin_out
it'll throw an exception, so the str_mgrgin_out := 'BLAH';
line never gets executed.
I think the error would be ORA-01403
.
Try adding an exception handler at the end as:
Exception
When Others Then
str_mgrgin_out := 'BLAH';
You might have to surround it with a BEGIN...END
as well so it would be:
CREATE OR REPLACE FUNCTION GET_MANAGERGIN2 (str_empgin_in IN varchar2)
RETURN varchar2
AS
str_mgrgin_out varchar2(10);
BEGIN
BEGIN
SELECT 'FOO' INTO str_mgrgin_out FROM dual WHERE str_empgin_in = '01356666';
str_mgrgin_out := 'BLAH';
Exception
When Others THen
str_mgrgin_out := 'BLAH';
END;
RETURN str_mgrgin_out;
END GET_MANAGERGIN2;
The select matches zero rows, with raises a NO_DATA_FOUND PL/SQL exception.
However NO_DATA_FOUND isn't recognized as an SQL error, merely the end of the result set.
Therefore when used in a SELECT, a null value is returned.
精彩评论