使用Oracle函数包裹选择

时间:2013-02-07 17:50:52

标签: oracle

在我看来,我正在编写一个函数来调用类似

的函数
select get_foo() from dual;

select * from table (get_foo);

返回与

相同的结果
select * from foo;

所以,我有一个编译的函数......

create or replace function get_foo return sys_refcursor as
  rc_foo sys_refcursor;
begin
  open rc_foo for 'select * from foo';
  return rc_foo;
end;

但是从双返回1行中选择get_foo()。

((ID=1,NAME=Sarah1),(ID=2,NAME=Sarah2),(ID=3,NAME=Sarah3),)

虽然select * from table(get_foo())给了我ORA-22905。

如何更改功能定义和/或调用以获得所需结果?

1 个答案:

答案 0 :(得分:1)

使用流水线功能。

例如:

SQL> create table foo(id , name) as select rownum, 'Sarah'||rownum from dual connect by level <= 3;

Table created.

SQL> create or replace package pipeline_test
  2  as
  3    type foo_tab is table of foo%rowtype;
  4    function get_foo
  5      return foo_tab PIPELINED;
  6  end;
  7  /

Package created.

SQL> create or replace package body pipeline_test
  2  as
  3    function get_foo
  4      return foo_tab PIPELINED
  5    is
  6      v_rc sys_refcursor;
  7             t_foo foo_tab;
  8
  9    begin
 10      open v_rc for select * from foo;
 11      loop
 12        fetch v_rc bulk collect into t_foo limit 100;
 13        exit when t_foo.count = 0;
 14        for idx in 1..t_foo.count
 15        loop
 16          pipe row(t_foo(idx));
 17        end loop;
 18      end loop;
 19    end;
 20  end;
 21  /

Package body created.

SQL> select * from table(pipeline_test.get_foo());

        ID NAME
---------- ---------------------------------------------
         1 Sarah1
         2 Sarah2
         3 Sarah3