域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過(guò)
一般變量使用我們都是放在函數(shù)里面,這里開(kāi)發(fā)需求,要在SQL直接使用變量,方便查找一些問(wèn)題,比如時(shí)間變量,要根據(jù)時(shí)間進(jìn)行篩選。
這里有三種方法可以實(shí)現(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;
通過(guò)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.通過(guò)定義參數(shù)實(shí)現(xiàn)
設(shè)置一個(gè)session級(jí)別的參數(shù),通過(guò)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)
補(bǔ)充:postgresql存儲(chǔ)函數(shù)/存儲(chǔ)過(guò)程用sql語(yǔ)句來(lái)給變量賦值
--定義變量
a numeric;
方式一:
1select sqla into a from table1 where b = '1' ; --這是sql語(yǔ)句賦值
方式二:
sql1:= 'select a from table1 where b = ' '1' ' ';
execute sql1 into a; --這是執(zhí)行存儲(chǔ)函數(shù)賦值
文章來(lái)源:腳本之家
來(lái)源地址:https://www.jb51.net/article/204214.htm
申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!