Following Sergey’s example here, https://stackoverflow.com/a/60834163/1513027
I’m trying to create an anonymous DO block rather than a function.
If I have the FETCH inside the block, it gives a syntax error, possibly wanting an INTO clause.
And it doesn’t matter whether the name of the cursor is in quotes.
DO
$$
DECLARE _query TEXT;
DECLARE _cursor CONSTANT refcursor := _cursor;
BEGIN
_query := 'select "Port", "Version", "AddDate" from "LatestLogEntry";';
OPEN _cursor FOR EXECUTE _query;
FETCH ALL FROM _cursor; -- syntax error at ;
END
$$;
If I have it outside, as in Sergey’s example, then it can’t see the cursor declared inside the block. And it does matter whether the name of the cursor is in quotes.
DO
$$
DECLARE _query TEXT;
DECLARE _cursor CONSTANT refcursor := '_cursor';
BEGIN
_query := 'select "Port", "Version", "AddDate" from "LatestLogEntry";';
OPEN _cursor FOR EXECUTE _query;
END
$$;
FETCH ALL FROM _cursor -- ERROR: cursor "_cursor" does not exist
2
Answers
The answer was hidden in a comment in one of the examples.
-- need to be in a transaction to use cursors.
Wrapping it in a transaction works.
In pgadmin this does work see screen below run postgres 15
as Sergey pointed out this has to be in a transaction, else you get the error message you get.
you can try to use it in an tranction