PostgreSQL: How to pass parameters from command line?

前端 未结 7 711
孤独总比滥情好
孤独总比滥情好 2020-12-23 15:42

I have a somewhat detailed query in a script that uses ? placeholders. I wanted to test this same query directly from the psql command line (outside the script

7条回答
  •  一个人的身影
    2020-12-23 16:10

    I've ended up using a better version of @vol7ron answer:

    DO $$
    BEGIN
        IF NOT EXISTS(SELECT 1 FROM pg_prepared_statements WHERE name = 'foo') THEN
            PREPARE foo(text,text,text) AS
                SELECT  * 
                FROM    foobar
                WHERE   foo = $1
                    AND bar = $2
                    OR  baz = $3;
        END IF;
    END$$;
    EXECUTE foo('foo','bar','baz');
    

    This way you can always execute it in this order (the query prepared only if it does not prepared yet), repeat the execution and get the result from the last query.

提交回复
热议问题