psql 将参数传递给 sql 脚本

Posted

技术标签:

【中文标题】psql 将参数传递给 sql 脚本【英文标题】:psql passing parameter to sql script 【发布时间】:2022-01-13 06:32:10 【问题描述】:

psql 9.2 版,服务器 12.0 版。

试图将参数传递给 sql 脚本, 执行脚本并传递参数:

psql --echo-queries -v ON_ERROR_STOP=0 -v TEST=100 postgresql://$curr_connection<< EOF 1 > $log_file 2>&1
\timing
\i sql_script.sql
EOF

请注意,我确认脚本在使用硬编码值(不带参数)时没有问题, 我想这可能与引号或其他内容中的参数有关,

sql_script.sql

INSERT INTO ACT_HI_COMMENT (action_,full_msg_,id_,message_,proc_inst_id_,task_id_,time_,type_,user_id_)
SELECT * FROM DBLINK ('host= MYHOST user=MYUSER password = MYPASS dbname=MYDB port=6432',
'SELECT ACT_HI_COMMENT.message_,ACT_HI_COMMENT.proc_inst_id_ FROM ACT_HI_COMMENT 
where ACT_HI_COMMENT.TASK_ID_ in (Select distinct CBAN_A.TASK_ID_ from CBAN_OSS_ACT_RU_VARIABLE_TASK 
where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = :TEST )')
 AS LINKTABLE (proc_inst_id_ character varying,task_id_ character varying,time_ timestamp without time zone,type_ character varying,
user_id_ character varying);

得到错误:

psql:/infadmin/inf/sql_script.sql:2: ERROR: syntax error at or near ":"
CONTEXT: while executing query on unnamed dblink connection

我还尝试在它周围加上一个单引号:'TEST'

INSERT INTO ACT_HI_COMMENT (action_,full_msg_,id_,message_,proc_inst_id_,task_id_,time_,type_,user_id_)
SELECT * FROM DBLINK ('host= MYHOST user=MYUSER password = MYPASS dbname=MYDB port=6432',
'SELECT ACT_HI_COMMENT.message_,ACT_HI_COMMENT.proc_inst_id_ FROM ACT_HI_COMMENT 
where ACT_HI_COMMENT.TASK_ID_ in
 (Select distinct CBAN_A.TASK_ID_ from CBAN_OSS_ACT_RU_VARIABLE_TASK
 where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = :'TEST' )') 
AS LINKTABLE (proc_inst_id_ character varying,task_id_ character varying,time_ timestamp without time zone,type_ character varying,user_id_ character varying);

得到错误:


psql:/infadmin/inf/sql_script.sql:2: ERROR: syntax error at or near "TEST"
LINE 2: ... where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = :'TEST' ..

【问题讨论】:

【参考方案1】:

怀疑,它没有工作,因为参数在单引号内, 我通过将引号内的整个字符串拆分为 2 来解决它, 由

' first_part '|| :'TEST'||'  <second_part>'

所以sql看起来像

INSERT INTO ACT_HI_COMMENT (action_,full_msg_,id_,message_,proc_inst_id_,task_id_,time_,type_,user_id_)
SELECT * FROM DBLINK ('host= MYHOST user=MYUSER password = MYPASS dbname=MYDB port=6432',
'SELECT ACT_HI_COMMENT.message_,ACT_HI_COMMENT.proc_inst_id_ FROM ACT_HI_COMMENT 
where ACT_HI_COMMENT.TASK_ID_ in
 (Select distinct CBAN_A.TASK_ID_ from CBAN_OSS_ACT_RU_VARIABLE_TASK
 where CBAN_OSS_ACT_RU_VARIABLE_TASK.GROUP_ID = '|| :'TEST'||' )')
AS LINKTABLE (proc_inst_id_ character varying,task_id_ character varying,time_ timestamp without time zone,type_ character varying,user_id_ character varying);


``

【讨论】:

以上是关于psql 将参数传递给 sql 脚本的主要内容,如果未能解决你的问题,请参考以下文章

如何将传递给我的 bash 脚本的所有参数传递给我的函数? [复制]

使用 argparser 将参数传递给入口点 python 脚本

将参数传递给 oracle 脚本

将函数参数传递给 sql 查询

通过 url 将参数传递给 sql server 报告服务

将 Access 表单上命令按钮的参数传递给 python 脚本