How do I declare variables in pgAdmin

前端 未结 3 1294
梦谈多话
梦谈多话 2021-02-20 05:38

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 = \'         


        
相关标签:
3条回答
  • 2021-02-20 05:49

    \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 the client in use:

    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 (was) pgScript, a local scripting extension of the pgAdmin3 query tool, where you can use local variables, comparable to what you can do in psql. The manual:

    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.

    But pgAdmin3 is unmaintained now, and pgAdmin4 does not include pgScript. Wasn't all that useful.

    0 讨论(0)
  • 2021-02-20 05:53

    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; 
    
    0 讨论(0)
  • 2021-02-20 06:03

    When trying to run scripts in pgAdmin I wanted the something similar where i wanted to store a value to use across multiple queries. This is what I found which is similar to SQL

    set session vars.batch_id = '82';
    
    select * from batches where batch_id = current_setting('vars.batch_id')::int;
    
    
    0 讨论(0)
提交回复
热议问题