Using variables when executing single command in PSQL
使用PSQL的变量时,我可以按如下方式运行它:
1 | psql -d DATABASE -v var="'123'" |
然后,当我在PSQL终端中键入以下内容时,我将访问变量
1 | SELECT * FROM TABLE WHERE COLUMN = :var; |
从文件中读取SQL时,此变量功能也有效:
1 | psql -d DATABASE -v var="'123'" -f file.sql |
但是当我尝试将SQL作为单个命令运行时:
1 | psql -d DATABASE -v var="'123'" -c"select * from table where column = :var;" |
我无法访问该变量并收到以下错误:
1 | ERROR: syntax error at OR near":" |
是否可以将变量传递给PSQL中的单个SQL命令?
事实证明,正如
1
2
3
4
5
6
7
8 -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来做我想做的事情:
1 | echo"select * from table where column = :var;" | psql -d DATABASE -v var="'123'" |