How to declare a variable in a PostgreSQL query

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

    You could also try this in PLPGSQL:

    DO $$
    DECLARE myvar integer;
    BEGIN
        SELECT 5 INTO myvar;
    
        DROP TABLE IF EXISTS tmp_table;
        CREATE TABLE tmp_table AS
        SELECT * FROM yourtable WHERE   id = myvar;
    END $$;
    
    SELECT * FROM tmp_table;
    

    The above requires Postgres 9.0 or later.

提交回复
热议问题