我需要测试一个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)。
但是,该功能对我来说是禁忌的,即它对我正在做的事情是外生的。
因此,我需要一种替代方法来获取该函数返回的三个游标的名称。 -我该怎么做?
答案 0 :(得分:1)
您可以将refcursor
强制转换为text
以获取其名称。
这是一个独立的小例子。
此函数返回两个refcursor
:
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;