Skip to content
Advertisement

Fetch multiple rows with PL/SQL procedure

Procedure:

create or replace PROCEDURE employee_project1 (
  emp_id   in  EMPLOYEES.EMPLOYEE_ID%TYPE,
  cur      out SYS_REFCURSOR
)
IS
BEGIN
  OPEN cur FOR
    SELECT p.project_id,
           p.project_name
    FROM   employees e
           INNER JOIN departments d
           ON ( e.department_id = d.department_id )
           INNER JOIN projects p
           ON ( p.department_id = e.department_id)
    WHERE  e.employee_id = emp_id;
END;

This procedure works for me. I am executing the procedure with below code:

Execution:

declare
    cur SYS_REFCURSOR;
    pro_id int;
    pro_name projects.project_name%TYPE;
begin
    employee_project1(43, cur);
    loop
        fetch cur into pro_id, pro_name;
        exit when cur%NOTFOUND;
        dbms_output.put_line(pro_id||' '||pro_name);
    end loop;
end;

I have to call the procedure in java with JDBC. So how can I call the procedure in java by above execution code?

Advertisement

Answer

Use a collection (which you can create using CREATE TYPE ... AS TABLE OF ...) or VARRAY (like the built-in VARRAYs SYS.ODCI*LIST) and BULK COLLECT INTO:

CREATE PROCEDURE employee_project (
  emp_id    in  EMPLOYEES.EMPLOYEE_ID%TYPE,
  pro_ids   out SYS.ODCINUMBERLIST,
  pro_names out SYS.ODCIVARCHAR2LIST
)
IS
BEGIN
  SELECT p.project_id,
         p.project_name
  BULK COLLECT INTO
         pro_ids,
         pro_names
  FROM   employees e
         INNER JOIN departments d
         ON ( e.department_id= d.department_id )
         INNER JOIN projects p
         ON ( p.department_id = d.department_id)
  WHERE  e.employee_id = emp_id;
END;
/

Or just return the cursor (without an INTO clause):

CREATE PROCEDURE employee_project (
  emp_id   in  EMPLOYEES.EMPLOYEE_ID%TYPE,
  cur      out SYS_REFCURSOR
)
IS
BEGIN
  OPEN cur FOR
    SELECT p.project_id,
           p.project_name
    FROM   employees e
           INNER JOIN departments d
           ON ( e.department_id= d.department_id )
           INNER JOIN projects p
           ON ( p.department_id = d.department_id)
    WHERE  e.employee_id = emp_id;
END;
/
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement