【问题标题】:Postgresql: how to get names of cursors returned by function?Postgresql:如何获取函数返回的游标名称?
【发布时间】:2019-12-15 23:06:05
【问题描述】:

我需要测试一个 psql 函数 (sp_create_refcursors),它返回 3 个游标。具体来说,我需要查看 3 个游标中的每一个“包含”哪些数据。

以下脚本包含执行测试的样板代码:

DO $$                    

BEGIN                    

 select sp_create_refcursors(); 

 //At this point I somehow need to get the names of the cursors returned by function sp_create_refcursors()

 FETCH ALL IN "? 1";
 FETCH ALL IN "?? 2";
 FETCH ALL IN "??? 3";

END;                     
$$;   

问题是我不知道函数 sp_create_refcursors() 返回的游标的名称,即我不知道用什么来代替“?”、“??”和“???”。

我知道 - 原则上 - 这个问题可以通过重新设计函数并将所有游标名称作为参数传递以获得预定义的游标名称来解决(参见 http://www.sqlines.com/postgresql/how-to/return_result_set_from_stored_procedure)。

但是,该功能对我来说是禁区,即它对我正在做的事情是外生的。

因此,我需要另一种方法来获取函数返回的三个游标的名称。 - 我该怎么做?

【问题讨论】:

    标签: postgresql cursors multiple-cursor


    【解决方案1】:

    您可以将refcursor 转换为text 以获取其名称。

    这是一个独立的小例子。

    这个函数返回两个refcursors:

    CREATE FUNCTION retref(
       OUT c1 refcursor,
       OUT c2 refcursor
    ) LANGUAGE plpgsql AS
    $$DECLARE
       xyz CURSOR FOR SELECT 42;
       abc CURSOR FOR SELECT 'value';
    BEGIN
       OPEN xyz;
       OPEN abc;
       c1 := xyz;
       c2 := abc;
    END;$$;
    

    我就是这样使用它的:

    BEGIN;
    
    WITH x AS (
       SELECT * FROM retref()
    )
    SELECT c1::text, c2::text
    FROM x;
    
     c1  | c2  
    -----+-----
     xyz | abc
    (1 row)
    
    FETCH ALL FROM xyz;
    
     ?column? 
    ----------
           42
    (1 row)
    
    FETCH ALL FROM abc;
    
     ?column? 
    ----------
     value
    (1 row)
    
    COMMIT;
    

    【讨论】:

    • 感谢您的回答……不过,我并没有真正明白。如果我无法引用它(因为我没有 refcursor 的名称),我该如何转换它?
    • 我添加了一个例子。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2010-11-09
    • 2019-10-22
    • 1970-01-01
    相关资源
    最近更新 更多