简体   繁体   中英

PostgreSQL: Declare a cursor for prepared statement

The following DECLARE fails:

PREPARE stmt(bigint) AS SELECT ...;
DECLARE crs CURSOR FOR stmt;

According to https://www.postgresql.org/docs/9.6/static/sql-declare.html , stmt has to be either SELECT or VALUES command.

I use PREPARE statement in a latency-critical section of the code in which thousands of quick queries are emitted. Parsing and generating a query plan each time would be performance killer. However, in some rare cases the query can return millions of records and the result doesn't fit into memory.

Is there a way to declare a cursor for prepared statement in PostgreSQL? If not, are there any workarounds?

https://www.postgresql.org/docs/9.1/static/ecpg-commands.html#ECPG-EXECUTING

This can be done through ECPG C library in c code. One can create prepared statement in C code as:

EXEC SQL PREPARE stmt1 FROM "SELECT oid,datname FROM pg_database WHERE oid > ?";

and then create cursor for that statement as:

EXEC SQL DECLARE foo_bar CURSOR FOR stmt1;

fetch result form cursor within infinite loop.

EXEC SQL OPEN foo_bar USING 100;


while(1){
    EXEC SQL FETCH NEXT FROM foo_bar INTO :dboid, :dbname;
}

This is available with 9.1 version of postgresql.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM