一般變量使用我們都是放在函數(shù)里面,這里開發(fā)需求,要在SQL直接使用變量,方便查找一些問題,比如時間變量,要根據(jù)時間進(jìn)行篩選。
這里有三種方法可以實現(xiàn)
1.psql命令使用變量
表數(shù)據(jù)如下:
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.通過定義參數(shù)實現(xiàn)
設(shè)置一個session級別的參數(shù),通過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存儲函數(shù)/存儲過程用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; --這是執(zhí)行存儲函數(shù)賦值
文章來源:腳本之家
來源地址:https://www.jb51.net/article/204214.htm
申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!