oracle 用函数查询怎么直接返回一个表?

我照着网上说的方法试了一下 ,比如
create or replace function FunTest return sys_refcursor as
l_cursor sys_refcursor;
begin
open l_cursor for select * from person1;
return l_cursor;
end;

但我试着用select funtest from dual 看了一下 他只是给我显示一个<cursor> 要点开才能显示返回的表
请问要怎么才能直接显示呢?

返回cursor的话,那么必须要cursor的手段来处理,不能作为查询语句的目的表。

如果需要在函数返回一个可以供查询语句使用的结果集,那么该函数的返回类型应该定义为一个索引表类型(一个table类型),然后在查询语句中使用table函数将函数返回的索引表转换成查询可以使用的目的表。示例如下:

1. 创建返回索引表所需的类型

create or replace type type_rec is object (idx integer, user_name varchar2(50));
create or replace type type_tb is table of type_rec;

2. 创建函数

create or replace function fn_return_tb
return type_tb
is
o_tb type_tb := type_tb();
i number := 0;
begin
  for v_rec in (select 1 as idx, 'Andy' as user_name from dual
  union select 2, 'Jack' from dual
  union select 3, 'Paul' from dual) loop
    o_tb.extend;
    i := i + 1;
    o_tb(i) := type_rec (v_rec.idx, v_rec.user_name);
  end loop;
  return o_tb;
end fn_return_tb;

3. 调用函数

select s.* 
from table(fn_return_tb()) s;

执行结果如下图,

温馨提示:答案为网友推荐,仅供参考
相似回答