简体   繁体   English

如何使用psql命令行将参数传递给.sql文件?

[英]How to pass parameters to .sql file using psql command line?

I have a bat file which have below command 我有一个下面命令的bat文件

"C:\Program Files (x86)\pgAdmin III\1.22\psql" -U postgres -h hostname -p 5432 -d TestDB -w -f 1.1.sql -v num_var=1.2

this command calls file 1.1.sql which have below script 此命令调用具有以下脚本的文件1.1.sql

DO $$
Begin 

If Exists (Select * from pg_statio_user_tables where relname = 'applicationsetting' ) then
update applicationsetting set value = :num_var
where applicationsettingid = '32bdba3b-39f6-4e43-947e-0bfdd4f5d561';
End IF;

End $$;

while clicking on bat file, I am getting this error 点击bat文件时,我收到此错误

psql:1.1.sql:9: ERROR:  syntax error at or near ":"
LINE 4: update demo set keyvalue = :num_var

However, the code works fine if I don't pass any variable and use static value in the update query. 但是,如果我没有传递任何变量并在更新查询中使用静态值,则代码可以正常工作。

EDIT 编辑

Code also works fine if I use the update query only without DO block and if clause. 如果我只使用没有DO块和if子句的更新查询,代码也可以正常工作。

No direct way, look into hacks here and here , eg: 没有直接的方法,看看这里这里的黑客,例如:

prepare: 准备:

db=# create table t (c int);
CREATE TABLE
db=# insert into t values (0);
INSERT 0 1

your working update: 你的工作更新:

db=# \set num_var 1
db=# update t set c = :num_var;
UPDATE 1
db=# table t;
 c
---
 1
(1 row)

now hack for "nested quoting": 现在破解“嵌套引用”:

db=# \set num_var 2
db=# \set hack 'begin update t set c = ':num_var'; end';
db=# do :'hack';
DO
db=# table t;
 c
---
 2
(1 row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将参数从bat文件或命令行传递到plpgsql函数? - How to pass parameters from a bat file or a command line to a plpgsql function? 如何使用NO脚本文件从命令行执行sql命令? - how to execute sql command from command line using NO script file? 如何在MySQL中使用命令行导入一个SQL文件? - How do I import an SQL file using the command line in MySQL? 如何使用MySQL命令行工具执行SQL文件? - How to execute a SQL file using MySQL command line tool? 在psql中执行.sql文件,从Excel单元格值传递参数 - Execute .sql file in psql, passing parameters from Excel cell values 使用命令行加载.sql文件 - loading .sql file using command line 通过 shell 脚本中的命令行参数将参数传递给 sql 文件 - Pass arguments to a sql file via command line arguments in shell script 如何使用 C# 运行 .sql 脚本,还需要为 .sql 文件中声明的参数传递值? - How to run .sql script using C#, also need to pass values for parameters that are declared in .sql file? PostgreSQL:使用 psql 命令行实用程序时 Windows 出现编码问题 - PostgreSQL: encoding problems on Windows when using psql command line utility 使用管道将函数生成的SQL查询重定向到psql命令 - Using pipes to redirect a function-generated SQL query to the psql command
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM