PostgreSQL: How to pass parameters from command line?

前端 未结 7 698
孤独总比滥情好
孤独总比滥情好 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:12

    You can also pass-in the parameters at the psql command-line, or from a batch file. The first statements gather necessary details for connecting to your database.

    The final prompt asks for the constraint values, which will be used in the WHERE column IN() clause. Remember to single-quote if strings, and separate by comma:

    @echo off
    echo "Test for Passing Params to PGSQL"
    SET server=localhost
    SET /P server="Server [%server%]: "
    
    SET database=amedatamodel
    SET /P database="Database [%database%]: "
    
    SET port=5432
    SET /P port="Port [%port%]: "
    
    SET username=postgres
    SET /P username="Username [%username%]: "
    
    SET /P bunos="Enter multiple constraint values for IN clause [%constraints%]: "
    ECHO you typed %constraints%
    PAUSE
    REM pause
    "C:\Program Files\PostgreSQL\9.0\bin\psql.exe" -h %server% -U %username% -d %database% -p %port% -e -v v1=%constraints% -f test.sql
    

    Now in your SQL code file, add the v1 token within your WHERE clause, or anywhere else in the SQL. Note that the tokens can also be used in an open SQL statement, not just in a file. Save this as test.sql:

    SELECT * FROM myTable
    WHERE NOT someColumn IN (:v1);
    

    In Windows, save the whole file as a DOS BATch file (.bat), save the test.sql in the same directory, and launch the batch file.

    Thanks for Dave Page, of EnterpriseDB, for the original prompted script.

提交回复
热议问题