在PSQL中执行单个命令时使用变量

时间:2017-07-19 14:15:56

标签: sql bash psql postgresql-9.3

使用PSQL变量时,我可以按如下方式运行:

psql -d database -v var="'123'"

当我在PSQL终端中键入以下内容时,我将可以访问变量var

select * from table where column = :var;

当从文件中读取SQL时,此变量功能也起作用:

psql -d database -v var="'123'" -f file.sql

但是当我尝试将SQL作为单个命令运行时:

psql -d database -v var="'123'" -c "select * from table where column = :var;"

我无法访问该变量并收到以下错误:

ERROR:  syntax error at or near ":"

是否可以将变量传递给PSQL中的单个SQL命令?

1 个答案:

答案 0 :(得分:2)

事实证明,正如man psql所解释的那样,-c命令仅限于“不包含psql特定功能的SQL”:

   -c command, --command=command
       Specifies that psql is to execute one command string, command, and then exit. This is useful in shell
       scripts. Start-up files (psqlrc and ~/.psqlrc) are ignored with this option.

       command must be either a command string that is completely parsable by the server (i.e., it contains no
       psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands
       with this option. To achieve that, you could pipe the string into psql, for example: echo '\x \\ SELECT
       * FROM foo;' | psql. (\\ is the separator meta-command.)

看起来我可以通过使用stdin传递SQL来做我想要的事情:

echo "select * from table where column = :var;" | psql -d database -v var="'123'"