You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PL/pgSQL游标疑问:逐行抓取及批量抓取设置方法

关于PL/pgSQL游标FETCH语句的解答

问题1:fetch from cursor1 into r是否逐行抓取结果行?

是的,默认情况下这条语句每次只会从游标中抓取一行数据到变量r中。你代码里的循环正是依赖这个逻辑逐行读取,直到游标没有更多数据(not found触发退出)。

问题2:能否设置单次从游标抓取100行?

完全可以,PL/pgSQL支持批量抓取,需要做以下调整:

  • 定义数组类型变量存储批量行数据
  • 使用FETCH NEXT 100 ROWS语法指定单次抓取行数
  • 遍历数组处理每一行数据

修改后的示例代码:

create or replace function func_cursor_2() 
returns setof numeric as $$
declare
    cursor1 CURSOR for select empno,ename, job from emp;
    r record;
    -- 定义存储批量记录的数组
    recs record[];
begin
    open cursor1;  
    loop  
        -- 单次抓取100行到数组
        fetch next 100 rows from cursor1 into recs;      
        exit when recs is null or array_length(recs, 1) = 0;
        
        -- 遍历数组中的每一行
        foreach r in array recs loop
            return next r.empno;
        end loop;
    end loop;
    close cursor1;
end;
$$ language plpgsql;

额外补充:在PL/pgSQL中处理这类返回结果集的场景,使用**隐式游标(FOR...IN循环)**更简洁,无需手动打开/关闭游标,示例如下:

create or replace function func_cursor_2() 
returns setof numeric as $$
declare
    r record;
begin
    for r in select empno,ename, job from emp loop
        return next r.empno;
    end loop;
end;
$$ language plpgsql;

这种写法更贴合PostgreSQL的惯用风格,代码也更精简。


内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:40:36