我定义了一个函数如下
CREATE OR REPLACE FUNCTION processActivityCommentTable() RETURNS INTEGER AS $$
DECLARE
activityCommentRow RECORD;
i RECORD;
activityId integer;
attachments text;
attachmentId integer;
cur1 CURSOR FOR SELECT ac.id, ac.attachments from activitycomment ac where ac.attachments is not null;
BEGIN
OPEN cur1;
FOR activityCommentRow in cur1
LOOP
RAISE NOTICE 'currently processing for %s ...', activityCommentRow.id;
-- can do some processing here
activityId = activityCommentRow.id;
attachments = activityCommentRow.attachments;
SELECT foo FROM regexp_split_to_table(attachments,E'{"id":') as foo;
FOR i in select * from foo
LOOP
select regexp_replace(i,'(,"name").*','') into attachmentId;
EXECUTE 'INSERT INTO attachment (activity_comment_id) values(' || attachmentId ||') where id= ' activityId;
END LOOP;
END LOOP;
CLOSE cur1;
END;
$$ LANGUAGE plpgsql;
执行时
select processActivityCommentTable();
它给了我以下错误
错误:游标“cur1”已在使用中 SQL状态:42P03 上下文:PL/pgSQL 函数 processactivitycommenttable() 第 12 行在 FOR over cursor
有人可以帮忙吗?
最佳答案
简答:在 FOR 循环中放置查询,而不是游标。
FOR
循环被记录为:
[ label ]
FOR target IN query LOOP
statements
END LOOP [ label ];
其中query
描述为:
The query used in this type of FOR statement can be any SQL command that returns rows to the caller: SELECT is the most common case, but you can also use INSERT, UPDATE, or DELETE with a RETURNING clause. Some utility commands such as EXPLAIN will work too.
这并不意味着游标的名称可能在那里。
您可以为它提供游标而不是游标的 SQL 查询。
如果游标确实需要在那里,从游标读取结果的命令是FETCH
,所以这种形式将被接受:
FOR activityCommentRow in FETCH ALL FROM cur1
或者 FETCH
的变体,例如如果只需要 3 行:
FOR activityCommentRow in FETCH 3 FROM cur1
关于postgresql - 使用游标执行函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931418/