PostgreSQL 中的用户定义变量 [英] User defined variables in PostgreSQL
问题描述
我想在 PostgreSQL 中实现以下 MySQL 脚本.
I have the following MySQL script which I want to implement in PostgreSQL.
SET @statement = search_address_query;
PREPARE dynquery FROM @statement;
EXECUTE dynquery;
DEALLOCATE PREPARE dynquery;
如何使用 PostgreSQL 定义用户定义的变量@statement".
How can I define user defined variable "@statement" using PostgreSQL.
推荐答案
Postgres 通常不在普通 SQL 中使用变量.但是你也可以这样做:
Postgres does not normally use variables in plain SQL. But you can do that, too:
SET foo.test = 'SELECT bar FROM baz';
SELECT current_setting('foo.test');
阅读手册中的自定义选项.
在 PostgreSQL 9.1 或更早版本中,您需要声明 custom_variable_classes
在你可以使用它之前.
In PostgreSQL 9.1 or earlier you needed to declare custom_variable_classes
before you could use that.
但是,您不能EXECUTE
动态 SQL 没有 PL(过程语言).您可以使用 DO
命令执行临时语句(但不能从中返回数据).或者使用 CREATE FUNCTION
创建一个执行动态 SQL 的函数(并且可以以任何可以想象的方式返回数据).
However, You cannot EXECUTE
dynamic SQL without a PL (procedural language). You would use a DO
command for executing ad-hoc statements (but you cannot return data from it). Or use CREATE FUNCTION
to create a function that executes dynamic SQL (and can return data in any fashion imaginable).
在使用动态 SQL 时一定要防止 SQL 注入.
Be sure to safeguard against SQL injection when using dynamic SQL.
相关:
这篇关于PostgreSQL 中的用户定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!