一般變量使用我們都是放在函數(shù)里面,這里開發(fā)需求,要在SQL直接使用變量,方便查找一些問題,比如時間變量,要根據(jù)時間進行篩選
這里有三種方法可以實現(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')::timest
c1 | c2 | c3
----+-------+----------------------------
4 | aaaaa | 2018-02-06 10:18:39.289523
(1 row)
補充:postgresql存儲函數(shù)/存儲過程用sql語句來給變量賦值
方式一:
select sqla into a from table1 where b = '1' ; --這是sql語句賦值
方式二:
sql1:= 'select a from table1 where b = ' '1' ' ';
execute sql1 into a; --這是執(zhí)行存儲函數(shù)賦值
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- PostgreSQL 正則表達式替換-使用變量方式
- postgresql 導入數(shù)據(jù)庫表并重設(shè)自增屬性的操作
- postgresql coalesce函數(shù)數(shù)據(jù)轉(zhuǎn)換方式
- postgresql 中的COALESCE()函數(shù)使用小技巧
- postgresql 實現(xiàn)修改jsonb字段中的某一個值
- postgresql 存儲函數(shù)調(diào)用變量的3種方法小結(jié)