简体   繁体   中英

Vanilla Postgres, select from prepared statement

I would like to use a prepared statement in a subquery. Simple example:

PREPARE get_series(int) AS SELECT * FROM generate_series(1,$1);

SELECT * FROM EXECUTE get_series(13);

But I am getting a syntax error.

As an alternative I could use a stored procedure, but the whole idea is to keep everything in the source code and prepared statements allow to invoke a parametrized query. Kind'a like UDP's but on the source code side.

Note: I'm using Postgres 10.2

EXECUTE is an SQL statement, not an expression that you can use in a FROM clause.

Try this:

EXECUTE get_series(13);

You cannot use EXECUTE in a subquery — only SELECT is allowed there.

I would say that you shouldn't use a prepared statement for this; maybe a set returning function is what you really need.

Actually it came to me that I can create as complex query as I want using CTEs. CTEs will make it easier to read and they will be parametrized through prepare statement. In the end the query still stays in the source code and in the source code I can extract the reusable parts.

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