postgresql - 从 shell 运行参数化查询时, ":"处或附近出现语法错误

标签 postgresql shell psql

我正在尝试从 shell 运行参数化查询。

但是当我运行时:

p='some stuff'
psql -d "dbname" -v v1="$p" -c "SELECT * FROM table WHERE name=:'v1'"

我收到以下错误:

ERROR:  syntax error at or near ":"

同时:

psql -d "dbname" -v v1="$p" -c "\echo :'v1'"

工作正常。 (按预期返回:'some stuff')

最佳答案

您不能在 -c 命令中使用 -v 中定义的变量(见下文)。尝试将命令传递到标准输入:

psql -d "dbname" -v v1="$p" <<< "SELECT * FROM table WHERE name=:'v1'"

来自document :

-c command

--command command

...

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.

...

-v 确实设置了 psql 的内部变量,这是psql 特定的功能。这就是您收到语法错误的原因。

关于postgresql - 从 shell 运行参数化查询时, ":"处或附近出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58621117/

相关文章:

PostgreSQL 时间戳字段

r - 如何将Shell变量引入R脚本?

ruby-on-rails - 如何使用基于多模式的应用程序 Rails 设置延迟作业。?

regex - PostgreSQL Regex 匹配带扩展名且无路径的长文件名模式

PostgreSQL:如何解决 "numeric field overflow"问题

postgresql - 如何启动 psql 命令行?

postgresql - 使用 psql、pgadmin 和 postgreSQL

python - 从python脚本获取shell脚本 "read"值

php - 使用 PHP 的 Mysql 转储

linux - 须藤: psql: command not found: can't fix it