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

Using variables when executing single command in PSQL

当使用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 命令?

事实证明,正如man psql所解释的那样,-c命令仅限于SQL,即"contains no psql-specific features":

   -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.)

看起来我可以通过使用标准输入传入 SQL 来做我想做的事:

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