站长网 经验 postgresql SQL语句变量的使用说明

postgresql SQL语句变量的使用说明

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 SQ

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 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

效果一样

2.\set使用变量

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.通过定义参数实现

设置一个session级别的参数,通过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语句来给变量赋值

–定义变量
a numeric;

方式一:

1select sqla into a from table1 where b = '1' ; –这是sql语句赋值

方式二:

sql1:= 'select a from table1 where b = ' '1' ' ';
execute sql1 into a; –这是执行存储函数赋值

本文来自网络,不代表站长网立场,转载请注明出处:https://www.tzzz.com.cn/html/jianzhan/jy/2021/0617/10936.html

作者: dawei

【声明】:站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。
联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: xwei067@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部