Oracle: Returning multiple rows in a function

Kerri Williams picture Kerri Williams · Mar 17, 2014 · Viewed 13.1k times · Source

I am trying to create a function which would return multiple rows.

Following is my function and type

create or replace type emp_type
(
first_name varchar2(20)
, last_name varchar2(20)
, depart_name varchar2(20)
)
/
create or replace function get_employee
 (loc in number)
return emp_type
as  
   emp_record emp_type;
begin
    select a.first_name, a.last_name, b.department_name into emp_record.first_name,
emp_record.last_name,emp_record.depart_name 
   from employees a, departments b 
    where a.department_id=b.department_id and location_id=loc;

   return(emp_record);  
end;

And I used

select get_employee(5) from dual;

I am getting "exact fetch returns more than requested number of rows " error. Later when I used rownum<2 in the select query I got "Reference to uninitialized composite".

Could you please help?

Thanks in Advance

Answer

Justin Cave picture Justin Cave · Mar 17, 2014

If you want to return a sys_refcursor, there is no reason to declare the object type or to try to return an object type. Just return a sys_refcursor.

create or replace function get_employee
  (p_loc in number)
  return sys_refcursor
as  
  l_rc sys_refcursor;
begin
  open l_rc
   for select a.first_name, a.last_name, b.department_name 
         from employees a, 
              departments b 
        where a.department_id=b.department_id 
          and location_id=p_loc;

  return l_rc; 
end;