Skip to Main Content
  • Questions
  • Raise NO_DATA_FOUND in a Get Function

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Charles.

Asked: July 27, 2020 - 12:20 pm UTC

Last updated: July 27, 2020 - 5:56 pm UTC

Version: 12c PL/SQL 12.1.0.2.0

Viewed 1000+ times

You Asked

Hi AT Team

I am tasked with maintaining similar code below.
The function returns a description from a state
code table.

The exception NO_DATA_FOUND is coded to do a RAISE.

When I test the function with a "bad" state code
value, the select from DUAL works, one empty row
is returned in TOAD.

There is a return coded with a NVL which will not
be executed when the NO_DATA_FOUND exception occurs.

When I code a query using the function against a
table with both good and bad (or missing) state code
values the query works returning descriptions for the
good state codes and null for the bad state codes.

What does the RAISE accomplish?

Thank you
Charles

---------------------------------------

select get_state_name('ZZ') from dual;


---------------------------------------

create function get_state_name 
       (p_state_cd_in in varchar2) 
       return varchar2 
    is
    ---- Variables
         v_state_name     varchar2(50) := null;
begin
   select   state_name 
     into   v_state_name
     from   state
    where   state_cd = p_state_cd_in
      and   rownum   < 2;

   return   nvl(v_state_name,'NA');

exception
   when no_data_found 
   then raise;
end get_state_name;



and Chris said...

Having

exception
  when ANY_EX then raise;


does nothing - it just reraises the exception. There's no value to having the handler here as-is.

The NVL will only come into play here if values for state.state_name can be null.

Note there's a subtle difference between SQL and PL/SQL - the NDF isn't raised when you call this in SQL. But it is in PL/SQL:

create or replace function f ( p varchar2 ) 
  return int as
  retval int;
begin

  select 1 
  into   retval
  from   dual
  where  dummy = p;
  
  return retval;

end f;
/

var v varchar2(1);

exec :v := f ( 'Y' );

ORA-01403: no data found

select f ( 'Y' ) from dual;

F('Y')   
   <null> 


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library