Oracle 函式中使用object table_type
阿新 • • 發佈:2018-11-22
create or replace function get_dept_emps(p_deptno in number)
return sys_refcursor
is
v_rc sys_refcursor;
begin
open v_rc for 'select empno, ename, mgr, sal from emp where deptno = :deptno' using p_deptno;
return v_rc;
end;
/
[email protected]>exec :rc :=get_dept_emps(10);
PL/SQL procedure successfully completed.
[email protected]>print rc;
EMPNO ENAME MGR SAL
---------- ---------- ---------- ----------
7782 CLARK 7839 2450
7839 KING 5000
7934 MILLER 7782 1300
[email protected]>select * from table(get_dept_emps(10));
select * from table(get_dept_emps(10))
*
ERROR at line 1:
ORA-22905: cannot access rows from a non-nested table item
create or replace type emptype as object(empno number,
ename varchar2(10),
mgr number,
sal number
);
/
create or replace type t_emptype as table of emptype;
/
create or replace function populate_emps(deptno in number := null)
return t_emptype
is
v_emptype t_emptype := t_emptype(); -- Declare a local table structure and initialize it
v_cnt number := 0;
v_rc sys_refcursor;
v_empno number;
v_ename varchar2(10);
v_mgr number;
v_sal number;
begin
v_rc := get_dept_emps(deptno);
loop
fetch v_rc into v_empno, v_ename, v_mgr, v_sal;
exit when v_rc%NOTFOUND;
v_emptype.extend;
v_cnt := v_cnt + 1;
v_emptype(v_cnt) := emptype(v_empno, v_ename, v_mgr, v_sal);
end loop;
close v_rc;
return v_emptype;
end;
/
[email protected]>select * from table(populate_emps(10));
EMPNO ENAME MGR SAL
---------- ---------- ---------- ----------
7782 CLARK 7839 2450
7839 KING 5000
7934 MILLER 7782 1300