postgresql - 使用游标执行函数时出错

标签 postgresql postgresql-9.1 plpgsql

我定义了一个函数如下

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/

相关文章:

sql - Postgres 循环更新记录

postgresql - 如何在 PostgreSQL 中调试触发器递归?

function - Postgres 创建具有记录类型功能的 View

node.js - Sequelize 一张表的多个计数

java - 当列类型为 bigint 时,PostgreSQL resultSet.getLong() 导致 ArrayIndexOutOfBoundsException

Python 2.7 + Django 1.7 + PostgreSQL 9.3 : I'm getting a UnicodeEncodeError when trying to save some text to my database. 给出了什么?

SQL 与 order by 连接

postgresql - 在 select 的 where 子句中调用 plpgsql 函数

mysql - 有限制的分组是如何工作的

sql - 根据条件删除重复行