如何用 refcursor 返回结果集

可以通过返回 Refcursor 类型的函数,或者out 类型的函数或 procedure 返回结果集。

一、返回refcursor 类型的函数

复制代码
create or replace function f_get_set(refcursor,refcursor)
returns setof refcursor
as $$
begin
  open $1 for select * from t1;
  return next $1;
  open $2 for select * from t1;
  return next $2;
end;
$$ language plsql;

begin;
  select * from get_set('a'::refcursor,'b'::refcursor);
  fetch all from a;
end
复制代码

二、通过OUT类型的函数参数

复制代码
create or replace function func_get_set_out(out cur_a refcursor,out cur_b refcursor)
as $$
begin
  open cur_a for select * from t1;
  open cur_b for select * from t1;
end;
$$ language plpgsql;

declare
  v_ref_cur1 refcursor;
  v_ref_cur2 refcursor;
  v_t1 t1%rowtype;
begin
  select * from get_set_out() into v_ref_cur1,v_ref_cur2;
  loop
    fetch v_ref_cur1 into v_t1;
    exit when v_ref_cur1%NOTFOUND;
    raise notice '%',v_t1.oid;
  end loop;
  loop
    fetch v_ref_cur2 into v_t1;
    exit when v_ref_cur2%NOTFOUND;
    raise notice '%',v_t1.oid;
  end loop;  
end;
复制代码

三、通过OUT类型的过程参数

复制代码
create or replace procedure proc_get_set_out(inout cur_a refcursor,inout cur_b refcursor)
as $$
begin
  open cur_a for select * from t1;
  open cur_b for select * from t1;
end;
$$ language plpgsql;

declare
  v_ref_cur1 refcursor;
  v_ref_cur2 refcursor;
  v_t1 t1%rowtype;
begin
  call proc_get_set_out(v_ref_cur1,v_ref_cur2);
  loop
    fetch v_ref_cur1 into v_t1;
    exit when v_ref_cur1%NOTFOUND;
    raise notice '%',v_t1.oid;
  end loop;
  loop
    fetch v_ref_cur2 into v_t1;
    exit when v_ref_cur2%NOTFOUND;
    raise notice '%',v_t1.oid;
  end loop;  
end;
复制代码

 

posted @   KINGBASE研究院  阅读(377)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示