一般变量使用我们都(dou)是句变放在函数里面,这里开发需求,使用说明要在SQL直接使用变量,句变(bian)方(fang)便查找一些问题,使用说明比如时间变(bian)量,句变要根据时间进行筛选。使用说明
这里有三种方(fang)法可以实现

1.psql命令使用(yong)变量(liang)

表(biao)数据如(ru)下:

hank=> select * from tb2;
c1 | c2 | c3
----+-------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
2 | dazui | 2018-02-06 10:08:08.542481
3 | wahah | 2018-02-06 10:08:15.468527
4 | aaaaa | 2018-02-06 10:18:39.289523
SQL文本如下
cat hank.sql
select * from tb2 where c2=:name and 句变(bian)c3>=:time;
通过psql查看
psql -v name="'hank'" -v time="'2018-02-06 10:08:00'" -f hank.sql
c1 | c2 | c3
----+------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
或者
psql -v name="'hank'" -v time=''2018-02-06 10:08:00'' -c '\i hank.sql'
c1 | c2 | c3
----+------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
效果(guo)一样
2.\set使用(yong)变量
hank=> \set name hank
hank=> \set time '2018-02-06 10:09:00'
hank=> select * from tb2 where c2=:'name' and c3>=:'time';
c1 | c2 | c3
----+------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
3.通过定义参数(shu)实现
设置一个session级别(bie)的参数,通过current_setting取值
hank=> set session "asasd.time" to "2018-02-06 10:09:00";
SET
hank=> select * from tb2 where c3 >= current_setting('asasd.time')::timestamp;
c1 | c2 | c3
----+-------+----------------------------
4 | aaaaa | 2018-02-06 10:18:39.289523
(1 row)
补充:postgresql存储函数/存储过程用sql语句来给变量赋值
--定(ding)义变量
a numeric;
方式一:
1select sqla into a from table1 where b = '1' ; --这(zhe)是使用说明sql语句赋值
方式二:
sql1:= 'select a from table1 where b = ' '1' ' ';
execute sql1 into a; --这是执行存储函数赋值(zhi)
文章来源:脚本之家
来源地址:https://www.jb51.net/article/204214.htm