Calling a function that returns a refcursor

依然范特西╮ 提交于 2019-11-28 11:03:28

Yes, use:

CREATE OR REPLACE FUNCTION function_1(refcursor) RETURNS refcursor AS $$
BEGIN
        OPEN $1 FOR SELECT * FROM some_table;
        RETURN $1;    
END;
$$ LANGUAGE plpgsql;

Result:

SELECT function_1('myowncursorname');
   function_1
-----------------
 myowncursorname
(1 row)

It looks like auto-generated name is <unnamed portal n>, where n is natural number (from 1).

EDIT:

As another way you could use pg_cursors view with such query to obtain generated cursor name:

SELECT name FROM pg_cursors WHERE statement LIKE 'SELECT * FROM some_table';

For example:

BEGIN;
SELECT function_1();
SELECT name FROM pg_cursors WHERE statement LIKE 'SELECT * FROM some_table';
COMMIT;

Result:

     function_1
--------------------
 <unnamed portal 3>
(1 row)

        name
--------------------
 <unnamed portal 3>
(1 row)

I'm not quite sure from wich version of Postgre this is available (in 8.4 it is valid) but i found quite easiest to define the cursor name when you declare it, like this:

CREATE OR REPLACE FUNCTION function_1() RETURNS refcursor AS $$
DECLARE
        ref_cursor REFCURSOR := 'mycursor';
BEGIN
        OPEN ref_cursor FOR SELECT * FROM some_table;
        RETURN (ref_cursor);    
END;
$$ LANGUAGE plpgsql;

And then you can get it like this:

BEGIN;
SELECT function_1();
FETCH 4   from  mycursor; 
COMMIT;

I find this method less cumbersome. Hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!