How to declare a variable in a PostgreSQL query

后端 未结 12 1451
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 09:34

How do I declare a variable for use in a PostgreSQL 8.3 query?

In MS SQL Server I can do this:

DECLARE @myvar INT
SET @myvar = 5

SELECT *
FROM somew         


        
12条回答
  •  温柔的废话
    2020-11-22 09:45

    Dynamic Config Settings

    you can "abuse" dynamic config settings for this:

    -- choose some prefix that is unlikely to be used by postgres
    set session my.vars.id = '1';
    
    select *
    from person 
    where id = current_setting('my.vars.id')::int;
    

    Config settings are always varchar values, so you need to cast them to the correct data type when using them. This works with any SQL client whereas \set only works in psql

    The above requires Postgres 9.2 or later.

    For previous versions, the variable had to be declared in postgresql.conf prior to being used, so it limited its usability somewhat. Actually not the variable completely, but the config "class" which is essentially the prefix. But once the prefix was defined, any variable could be used without changing postgresql.conf

提交回复
热议问题