循环遍历游标结果

时间:2015-10-29 13:07:31

标签: database postgresql stored-procedures cursor plpgsql

我正在尝试遍历游标(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 使用列ID,名称

的表商店

1 个答案:

答案 0 :(得分:1)

首先,你的功能不会返回任何东西,你只需要发出通知。在pgAdmin中,这些将在“消息”窗格中输出,而不是在“数据输出”窗格中输出。

我假设您想要实际返回值...
但通常,您不需要显式游标来循环。使用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;

相关答案以及更多详情和解释: