postgresql 如何在 pgAdmin 中声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23561408/
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 01:26:35  来源:igfitidea点击:

How do I declare variables in pgAdmin

postgresqlvariablespsqlpgadmin

提问by dagda1

If I am in the psql terminal then I can declare and use a variable like this:

如果我在 psql 终端中,那么我可以声明并使用这样的变量:

\set message_id soifsdaofisd.gmail.com;
select * from emails where message_id = ':message_id';

How can I do this in pgAdmin?

我怎样才能在 pgAdmin 中做到这一点?

I get an error when ever I try this in pgAdmin:

我在 pgAdmin 中尝试此操作时收到错误消息:

ERROR: syntax error at or near "CALAdkA4YC0" LINE 3: set message_id soifsdaofisd.gmail.com.

错误:“CALAdkA4YC0”处或附近的语法错误第 3 行:设置 message_id soifsdaofisd.gmail.com。

回答by Erwin Brandstetter

\setis a feature of psql (the interactive command line terminal) and not available in pgAdmin.

\set是 psql(交互式命令行终端)的一个特性,在 pgAdmin 中不可用。

PostgreSQL does not normally use variables in plain SQL. You would use PL/pgSQL codein an anonymous block (DOstatement) or in a function.

PostgreSQL 通常不在普通 SQL 中使用变量。您将在匿名块(语句)或函数中使用PL/pgSQL 代码DO

However, you can(ab)use customized options, for server-side "variables", independent of which client you are using at the moment:

但是,您可以(ab)为服务器端“变量”使用自定义选项,而与您目前使用的客户端无关:

SET foo.test = 'SELECT bar FROM baz';
SELECT current_setting('foo.test');

Details in this related answer:
User defined variables in PostgreSQL

此相关答案中的详细信息:
PostgreSQL 中的用户定义变量

And there is also pgScript, a local scripting extension in the pgAdmin query tool, where you can use local variables, comparable to what you can do in psql. Per documentation:

并且还有pgScript,这是 pgAdmin 查询工具中的本地脚本扩展,您可以在其中使用本地变量,与您在 psql 中所做的相当。根据文档:

You can run pgScript scripts by selecting Execute pgScript from the Query menu instead of Execute, or you press the Execute pgScript toolbar button, or you press the F6 function key.

您可以通过从查询菜单中选择执行 pgScript 而不是执行,或者按下执行 pgScript 工具栏按钮,或者按下 F6 功能键来运行 pgScript 脚本。

Details in the pgScript scripting language reference.

pgScript 脚本语言参考中的详细信息。

回答by Tim Kessler

An alternative is to create a view.

另一种方法是创建视图。

-- create view to store variable list
create view script_variables as select 'soifsdaofisd.gmail.com' as message_id;
-- run your script
select * from emails where message_id = (select message_id from script_variables);
-- clean up 
drop view script_variables;