How to declare a variable in a PostgreSQL query

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

    This solution is based on the one proposed by fei0x but it has the advantages that there is no need to join the value list of constants in the query and constants can be easily listed at the start of the query. It also works in recursive queries.

    Basically, every constant is a single-value table declared in a WITH clause which can then be called anywhere in the remaining part of the query.

    • Basic example with two constants:
    WITH
        constant_1_str AS (VALUES ('Hello World')),
        constant_2_int AS (VALUES (100))
    SELECT *
    FROM some_table
    WHERE table_column = (table constant_1_str)
    LIMIT (table constant_2_int)
    

    Alternatively you can use SELECT * FROM constant_name instead of TABLE constant_name which might not be valid for other query languages different to postgresql.

提交回复
热议问题