PostgreSQL 中的用户定义变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14261035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:43:12  来源:igfitidea点击:

User defined variables in PostgreSQL

postgresqlvariablesdynamic-sql

提问by ishk

I have the following MySQL script which I want to implement in PostgreSQL.

我有以下我想在 PostgreSQL 中实现的 MySQL 脚本。

 SET @statement = search_address_query;
      PREPARE dynquery FROM @statement;
      EXECUTE dynquery;
      DEALLOCATE PREPARE dynquery;

How can I define user defined variable "@statement" using PostgreSQL.

如何使用 PostgreSQL 定义用户定义的变量“@statement”。

回答by Erwin Brandstetter

PostgreSQL does not normally use variables in plain SQL. But you cando that, too:

PostgreSQL 通常不在普通 SQL 中使用变量。但你也可以这样做:

SET foo.test = 'SELECT bar FROM baz';

SELECT current_setting('foo.test');

Read about Customized Options in the manual.

阅读手册中的自定义选项

In PostgreSQL 9.1 or earlier you needed to declare custom_variable_classesbefore you could use that.

PostgreSQL 9.1 或更早版本中,您需要先声明custom_variable_classes才能使用它。

However, You cannotEXECUTEdynamic SQLwithout a PL (procedural language). You would use a DOcommand for executing ad-hoc statements (but you cannot return data from it). Or use CREATE FUNCTIONto create a function that executes dynamic SQL (and can return data in any fashion imaginable).

但是,如果没有 PL(过程语言),您就不能EXECUTE动态 SQL。您可以使用DO命令来执行临时语句(但不能从中返回数据)。或者用于CREATE FUNCTION创建一个执行动态 SQL 的函数(并且可以以任何可以想象的方式返回数据)。

Be sure to safeguard against SQL injection when using dynamic SQL.

使用动态 SQL 时一定要防止 SQL 注入。

Related question about custom variables:
Is there a way to define a named constant in a PostgreSQL query?

关于自定义变量的相关问题:
有没有办法在 PostgreSQL 查询中定义命名常量?