1

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
BWhite
  • 713
  • 1
  • 7
  • 24

2 Answers2

1

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.

BEGIN;
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

COMMIT
BWhite
  • 713
  • 1
  • 7
  • 24
0

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.

enter image description here

you can try to use it in an tranction

nbk
  • 45,398
  • 8
  • 30
  • 47
  • And there it is, right there in the original. "Cursors are visible in the transaction scope so you should use this within one transaction." – BWhite Dec 16 '22 at 23:52