如何在同一脚本中的多个选择上使用常量值?

问题描述 投票:0回答:1

我正在尝试编写可供不熟悉 PostgreSQL 的人使用的脚本。目标是验证一些使用这些表作为源的报告。为了方便起见,我想对选择参数使用常量变量,例如:

var1 numeric = 123;  
var2 numeric = 022020;
 
select * from table1 t1 inner join table4 t4 on t1.a = t4.a where t1.b = var1 and t1.c = var2; 

select * from table2 t2 inner join table4 t4 on t2.a = t4.a where t2.b = var1 and t2.c = var2; 

select * from table3 t3...

我尝试使用

DO
WITH
TEMP TABLE
,但脚本不会以易于读取和更改变量的格式返回分割的选择。

postgresql constants multiple-select-query
1个回答
0
投票

我认为您正在寻找

\set
命令:

cat script.sql

postgres@davinci:~$ cat voo.sql 
\set var1 123
\set var2 022020

select * from table1 t1 inner join table4 t4 on t1.a = t4.a where t1.b = var1 and t1.c = var2;
select * from table2 t2 inner join table4 t4 on t1.a = t4.a where t2.b = var1 and t2.c = var2;
select * from table3 t3...

然后,您可以使用

psql
调用脚本,如下所示:

psql -h ${HOST} -U ${USER} ${DATABASE} < script.sql

如果您愿意,您也可以从

\set
中调用这些
psql
命令。

© www.soinside.com 2019 - 2024. All rights reserved.