简体   繁体   English

香草Postgres,从准备好的语句中选择

[英]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. 有点像UDP,但在源代码方面。

Note: I'm using Postgres 10.2 注意:我使用的是Postgres 10.2

EXECUTE is an SQL statement, not an expression that you can use in a FROM clause. EXECUTE是一个SQL语句,而不是可以在FROM子句中使用的表达式。

Try this: 尝试这个:

EXECUTE get_series(13);

You cannot use EXECUTE in a subquery — only SELECT is allowed there. 您不能在子查询中使用EXECUTE那里只允许SELECT

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. 实际上,我想到可以使用CTE创建尽可能复杂的查询。 CTEs will make it easier to read and they will be parametrized through prepare statement. CTE将使其更易于阅读,并且将通过prepare语句进行参数化。 In the end the query still stays in the source code and in the source code I can extract the reusable parts. 最后,查询仍然停留在源代码中,在源代码中,我可以提取可重复使用的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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