如何从单个OUT游标中获取多个游标

时间:2020-08-03 13:47:11

标签: postgresql plpgsql database-cursor

我有这样的功能:

CREATE OR REPLACE FUNCTION get_request
(IN p_id TEXT, 
OUT c_request REFCURSOR)
AS 
$BODY$
BEGIN

DECLARE 

    cur_1 CURSOR FOR select id, title, doc_url, icon_url
                      from request_attachments
                      where request_attachments.id = requests.id;
        
    cur_2 CURSOR FOR  select users.id user_id, 
                              users.name user_name, 
                              users.email user_email,
                              users.picture_url user_picture, 
                              request_comments.ts, 
                              request_comments."comment"
                        from request_comments, users
                        where request_comments.id = p_id and request_comments.user_id = users.id
                        order by request_comments.id desc, request_comments.ts desc;
        

BEGIN
open c_request for
    select requests.center_id, 
    cur_1 attachments,
    cur_2 comments
    from requests
    where id = p_id;
    
END;
END;
$BODY$
LANGUAGE plpgsql;

我想从此函数的c_request游标中定义的游标中获取值。 我写了这样的东西:

c_kur = get_request('some id here');
loop
  fetch c_kur into r_kur;
  IF NOT FOUND THEN EXIT; END IF;



    c_kur2 = r_kur.cur_1;
    loop
      fetch c_kur2 into r_kur2;
      IF NOT FOUND THEN EXIT; END IF;
      raise info 'user_id: %, comment: %', r_kur2.user_id, r_kur2."comment";  --THIS IS WHERE I WANT TO SEE THOSE VALUES
    end loop;




end loop;
close c_kur;

但是它似乎不起作用。如何从此函数获取cur_1和cur_2值 像上面这样的嵌套循环中?

我收到此错误:

NOTICE:  cursor "cur_1" does not exist 34000

1 个答案:

答案 0 :(得分:0)

没有人能够帮助我,但是我已经通过完全重写此功能来解决了这个问题。现在,我有两个附加的“ helper”函数,它们分别返回游标,而这个主要的get_request函数仅返回c_request游标,而没有cur_1和cur_2游标(它们由助手函数处理)。

它的运行速度较慢,但​​是可以。 ;)