How to declare a variable in a PostgreSQL query

后端 未结 12 1521
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    It depends on your client.

    However, if you're using the psql client, then you can use the following:

    my_db=> \set myvar 5
    my_db=> SELECT :myvar  + 1 AS my_var_plus_1;
     my_var_plus_1 
    ---------------
                 6
    

    If you are using text variables you need to quote.

    \set myvar 'sometextvalue'
    select * from sometable where name = :'myvar';
    

提交回复
热议问题