Calling a function that returns a refcursor

后端 未结 2 1406
陌清茗
陌清茗 2020-12-10 03:53

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

CREATE OR REPLACE FUNCTION functio         


        
相关标签:
2条回答
  • 2020-12-10 04:18

    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)
    
    0 讨论(0)
  • 2020-12-10 04:36

    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.

    0 讨论(0)
提交回复
热议问题