How do I declare variables in pgAdmin

跟風遠走 提交于 2019-12-06 22:22:16

问题


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

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

How can I do this in pgAdmin?

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

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


回答1:


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

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

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

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

Details in this related answer:
User defined variables in 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:

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.

Details in the pgScript scripting language reference.




回答2:


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; 


来源:https://stackoverflow.com/questions/23561408/how-do-i-declare-variables-in-pgadmin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!