遍历游标结果

looping through cursor results

我正在尝试遍历游标 (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 Table stores with columns id,name

首先,你的函数没有return任何东西,你只是产生通知。在 pgAdmin 中,这些将在 "Messages" 窗格中输出,而不是在 "Data Output" 窗格中输出。

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

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;

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

  • Update record of a cursor where the table name is a parameter
  • Loop on tables with PL/pgSQL in Postgres 9.0+