欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

postgresql SQL語(yǔ)句變量的使用說(shuō)明

 更新時(shí)間:2021年01月16日 11:22:42   作者:dazuiba008  
這篇文章主要介紹了postgresql SQL語(yǔ)句變量的使用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

一般變量使用我們都是放在函數(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;

方式一:

select 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ù)賦值

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

最新評(píng)論