I’m migrating an Oracle PLSQL SP to be compatible with Postgres plpgsql (version PostgreSQL 13.6 on x86_64-pc-linux-gnu, compiled by x86_64-pc-linux-gnu-gcc (GCC) 7.4.0, 64-bit).
The exception block of the PLSQL SP has the below code:
exception
when others then
if CURR1%isopen then
close SPV_RECON_INFO;
end if;
open CURR1 for execute select sysdate from dual;
END;
How can %isopen be implemented in Postgres?
3
Answers
PostgreSQL cursors do not support %ISOPEN or %NOTFOUND. To address this problem %ISOPEN can be replaced by a boolean variable declared internally in the procedure and is updated manually when the cursor is opened or closed.
http://wiki.openbravo.com/wiki/PL-SQL_code_rules_to_write_Oracle_and_Postgresql_code
That is simple. You have to assign a name to the cursor variable, then you can search for that cursor in
pg_cursors
. If there is a row with thatname
, the cursor is open.Here is a self-contained example:
If you do not assign a name, PostgreSQL will generate a name (but you don’t know what the name is).
I often found it convenient in cases like this to create a function that emulates Oracle. In his case something like:
Then your code becomes something like:
Of course you need to have preset the cursor name as Laurenz Albe has pointed out. Sample test case.
results:
cursor_isopen(‘closed-cursor’) returned f
cursor_isopen(‘open-cursor’) returned t. First table name: task_states