Pass a bounded cursor to a function

38 Views Asked by At

There are many examples to open a cursor inside a function, but I can't find the opposite.

Take a look to this simple function:

CREATE FUNCTION public.try_ref_cursor(IN rc refcursor)
    RETURNS bigint
    LANGUAGE 'plpgsql'
    
AS $BODY$
declare
/*
    IN rc refcursor
    RETURNS bigint
    
*/
    _rec record;
    _i  integer=0;
begin

    open rc;

    for _rec in rc loop
        _raise notice '%', _rec
        _i=_i+1;
    end loop;

    return _i;
end;
$BODY$;

the function call:

declare
    mycursor cursor for select a, b,c from sometable;
    mycount integer;
begin
    mycount=public.try_ref_cursor(mycursor);
end;

My actual need is to iterate on a recordset (coming from different tables) with some fields always present (think to the interface pattern) and do some checks and aggregations, returning at the end a jsonb.

Ok I can rewrite the function passing an array of record, but it doesn't seem very efficient.

any ideas?

1

There are 1 best solutions below

0
Pavel Stehule On

refcursor is name of cursor, and it is just text. You can pass it in both directions without any problems.