postgresql中的嵌套游标循环

时间:2016-09-13 09:05:43

标签: postgresql cursor plpgsql

我是postgresql的新手,并且遇到有关嵌套循环的问题。这是我的代码:

CREATE TABLE q_39442172
(
   id character varying,
   event_id character varying,
   createdat character varying
);


insert into q_39442172 values('id1', 'event_1', '20160789');
insert into q_39442172 values('id2', 'event_2', '20160689');
insert into q_39442172 values('id3', 'event_3', '20160679');
insert into q_39442172 values('id4', 'event_4', '20160579');
insert into q_39442172 values('id3', 'event_3', '20160579');
insert into q_39442172 values('id2', 'event_5', '20160379');
insert into q_39442172 values('id1', 'event_6', '20160339');


create or replace function query_event_sequence() returns table( r_id character varying, r_events text ) as
$$
declare
    vc_id            character varying;
    vc_event_id      character varying;
begin
    for ref_User in execute 'select distinct id from q_39442172 order by id' loop
        vc_id   := ref_User.id;
        r_id    := ref_User.id;

        for ref_Event in execute 'select event_id from q_39442172 where id = ' || vc_id loop
            vc_event_id := ref_Event.event_id;
            r_events    := concat_ws( ',', r_events, vc_event_id );
        end loop;

        raise notice '%: %', r_id, r_events;
        return next;
    end loop;
end;
$$
language plpgsql;

我得到的例外:

NOTICE:  id1: event_6,event_1
ERROR:  cursor "<unnamed portal 2>" already in use
CONTEXT:  PL/pgSQL function query_event_sequence() line 13 at OPEN
********** Error **********

ERROR: cursor "<unnamed portal 2>" already in use
SQL state: 42P03

实际上,使用array_agg可以做我想做的事情,但我很困惑为什么我的代码中的嵌套游标循环不起作用。

1 个答案:

答案 0 :(得分:1)

您不需要功能或光标。单个SQL语句将执行:

select string_agg(concat_ws(',', event_id, id), ',' order by id)
from q_39442172 
where id in (select id from q_39442172)