从存储过程返回行而不使用ref_cursor

时间:2013-01-21 11:57:51

标签: oracle plsql

我有一个像

这样的存储过程
create procedure Sample(sid out number,sname out varchar2) is
begin
select id,name into sid,sname from emp;
end;

我的结果应该是

id      name
------------
1      Sai
5      Hari
8      Nari

我无法获得上面数组类型的结果如何才能得到它(没有ref_cursor和ref_cursor)?

1 个答案:

答案 0 :(得分:4)

“没有ref_cursor和ref_cursor”有点令人困惑。没有和有?

但是如果不允许REF游标,你的输出必须是数组输出。

例如:

创建这些类型:

create type myemptype as object (id number, name varchar2(200));
/
create type myemptab as table of myemptype;
/

然后:

SQL> create or replace procedure Sample(p_tab  out myemptab) is
  2  begin
  3    p_tab := myemptab();
  4    for r_emp in (select id,name from emp order by id)
  5    loop
  6      p_tab.extend;
  7      p_tab(p_tab.last) := myemptype(r_emp.id, r_emp.name);
  8    end loop;
  9  end;
 10  /

Procedure created.

SQL>
SQL> declare
  2    t_emp  myemptab;
  3  begin
  4    sample(t_emp);
  5    for idx in 1..t_emp.count
  6    loop
  7      dbms_output.put_line(t_emp(idx).id || chr(9) || t_emp(idx).name);
  8    end loop;
  9  end;
 10  /
1       Sai
5       Hari
8       Nari

PL/SQL procedure successfully completed.

或更好,作为流水线功能:

SQL> create or replace function Sample
  2  return myemptab pipelined
  3  is
  4  begin
  5    for r_emp in (select id,name from emp order by id)
  6    loop
  7      pipe row ( myemptype(r_emp.id, r_emp.name) );
  8    end loop;
  9  end;
 10  /

Function created.


SQL> col name format a10
SQL> select * from table(sample);

        ID NAME
---------- ----------
         1 Sai
         5 Hari
         8 Nari

使用标量数组编辑:

SQL> create type myempidtab as table of number;
  2  /

Type created.

SQL> create type myempnametab as table of varchar2(20);
  2  /

Type created.

SQL> create or replace procedure Sample(p_id out myempidtab ,p_name out myempnametab) is
  2  begin
  3    p_id := myempidtab();
  4    p_name := myempnametab();
  5    for r_emp in (select id,name from emp order by id)
  6    loop
  7      p_id.extend;
  8      p_name.extend;
  9      p_id(p_id.last) := r_emp.id;
 10      p_name(p_name.last) := r_emp.name;
 11    end loop;
 12  end;
 13  /

Procedure created.

SQL> declare
  2    t_id    myempidtab;
  3    t_name  myempnametab;
  4  begin
  5    sample(t_id, t_name);
  6    for idx in 1..t_id.count
  7    loop
  8      dbms_output.put_line(t_id(idx) || chr(9) || t_name(idx));
  9    end loop;
 10  end;
 11  /
1       Sai
5       Hari
8       Nari

PL/SQL procedure successfully completed.

SQL>