【问题标题】:looping through cursor results遍历游标结果
【发布时间】:2015-10-29 13:07:30
【问题描述】:

我正在尝试遍历游标(plpgsql)结果,但不知何故,输出控制台上没有打印任何内容。

create or replace function curs() returns refcursor as 
$body$
declare
    curs cursor for select id from stores;
    store stores.id%TYPE;
begin
    open curs;
    fetch curs into store;
    loop
    exit when not found;
        raise notice 'Value: %',store;
    end loop;
    close curs;
end
$body$ language plpgsql;

select curs();

如何实现正确的循环?

数据库版本:9.0 表 stores 列 id,name

【问题讨论】:

  • 此问题还应提供表定义和您的 Postgres 版本。
  • @ErwinBrandstetter 更新了问题
  • 但这不是表定义。表定义是一个完整的 CREATE TABLE 脚本,显示数据类型和约束,或者你在 psql 中使用 \d tbl 得到的结果。

标签: database postgresql stored-procedures cursor plpgsql


【解决方案1】:

首先,你的函数不返回任何东西,你只是产生通知。在 pgAdmin 中,这些将在“消息”窗格中输出,而不是在“数据输出”窗格中。

我假设您想要实际返回值...
但通常,您不需要显式游标来循环。使用 FOR 循环中更方便的 implicit 光标:

CREATE OR REPLACE FUNCTION test_loop()
  RETURNS SETOF int AS 
$func$
DECLARE
   _id int;  -- assuming data type integer
BEGIN
   FOR _id IN
      SELECT id FROM stores ORDER BY id
   LOOP
      RETURN NEXT _id;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

注意调用语法:

SELECT * FROM test_loop();

通常,您甚至不需要循环。只是简单的 SQL ...

CREATE OR REPLACE FUNCTION test_loop1()
  RETURNS SETOF int AS 
$func$
BEGIN
   RETURN QUERY
   SELECT id FROM stores ORDER BY id;
END
$func$  LANGUAGE plpgsql;

可以简化为 SQL 函数:

CREATE OR REPLACE FUNCTION test_loop2()
  RETURNS SETOF int AS 
$func$
   SELECT id FROM stores ORDER BY id;
$func$  LANGUAGE sql;

更多细节和解释的相关答案:

【讨论】:

  • 是的。第一个示例有效。但是如果我不想使用循环怎么办?然后如何单独读取值并返回它们?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
相关资源
最近更新 更多