Calling a function that returns a refcursor

Ken Chan picture Ken Chan · Jul 13, 2011 · Viewed 32.2k times · Source

I am using Postgresql 8.3 and have the following simple function that will return a refcursor to the client

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

Now , I can use the following SQL commands to call this function and manipulate the returned cursor ,but the cursor name is automatically generated by the PostgreSQL

BEGIN;
SELECT function_1();  --It will output the generated cursor name , for example , "<unnamed portal 11>" ;
FETCH 4   from  "<unnamed portal 11>"; 
COMMIT;

Besides , explicitly declaring the cursor name as the input parameter of the function as described by 38.7.3.5. Returning Cursors.Can I declare my own cursor name and use this cursor name to manipulate the returned cursor instead of Postgresql automatically generates for me ? If not , are there any commands that can get the generated cursor name ?

Answer

VoidMain picture VoidMain · Sep 18, 2012

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.