我有一个递归 PL/PgSQL 函数,它使用这样的绑定参数化游标:
create or replace function test_cursor(rec boolean) returns void as $$
declare
cur cursor(a int) for select * from generate_series(1,a);
begin
for c in cur(3) loop
if rec then
perform test_cursor(false);
end if;
end loop;
end;
$$ language plpgsql;
当函数递归调用自身时,会报错:
select test_cursor(true)
Code: 42P03, ErrorMessage: cursor "cur" already in use
显然,我的光标范围不限于单个函数调用。在谷歌搜索解决方法后,我在邮件列表档案中发现了这条消息,其中提到未绑定的游标没有这个限制,即:
declare
mycursor refcursor;
begin
open mycursor for ...;
end;
但是我看不到如何参数化未绑定的游标。另外,我不能使用for...loop
未绑定的游标:
-- 42601: cursor FOR loop must use a bound cursor variable
create or replace function test_cursor(rec boolean) returns void as $$
declare
cur refcursor;
begin
open cur for select * from generate_series(1,3);
for c in cur loop
if rec then
perform test_cursor(false);
end if;
end loop;
close cur;
end;
$$ language plpgsql;
有人可以建议一种替代方法吗?
PS。我正在移植大量使用递归和参数化游标的 Oracle 存储过程。在我用全局范围的游标遇到这个问题之前,转换似乎很简单。