简体   繁体   English

准备好的语句-使用参数指定表名

[英]prepared statement - using parameter to specify table name

using pgadmin4, postgres 9.6 on windows 10 在Windows 10上使用pgadmin4,postgres 9.6

I'm trying to use parameter to specify table name in a prepared statement as in the code below. 我正在尝试使用参数在准备好的语句中指定表名,如下面的代码所示。 However I do get a syntax error as below. 但是我确实收到如下语法错误。 Note that I'm able to use the parameters with a where condition et al. 请注意,我可以将参数与where条件等配合使用。

Query 询问

prepare mySelect(text) as 
    select * 
        from $1
        limit 100;

execute mySelect('some_table');

pgAdmin message pgAdmin消息

ERROR:  syntax error at or near "$1"
LINE 3:      from $1
                  ^
SQL state: 42601
Character: 50

It is not possible. 这不可能。 The prepare statement is persistent execution plan - and execution plan contains pined source of data - so tables, column names cannot be mutable there. prepare语句是持久性执行计划-执行计划包含固定的数据源-因此表,列名不能在此处可变。

When you change table, columns, then you change the semantic of query - you will got different execution plan and then this behave is not possible in prepared statements. 当更改表,列时,然后更改查询的语义-您将获得不同的执行计划,这在准备好的语句中是不可能的。 The main use case of prepared statements is reusing of execution plans - plan once, execute more. 准备好的语句的主要用例是重用执行计划-计划一次,再执行一次。 But there are some principal limits - only some parameters can be changed. 但是有一些主要限制-只能更改某些参数。

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

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