有關Sql中時間范圍的問題


背景

有時候需要利用sql中處理關於時間的判別問題,簡單的如比較時間的早晚,判斷一個時間是否在一段時間內的問題等。如果簡單將時間判斷與數值比較等同,那就會出現一些問題。

處理方式

處理Sql時間范圍的問題有兩種比較方式。

當前時間

select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') as Nowtime from dual; 
//2020-04-02 16:25:42

1、將日期轉換為字符串再比較

select sysdate nowtime from dual where to_char(sysdate,'yyyymmdd hh24:mi:ss') between '20200401' and '20200403';
//02-APR-20,時間范圍是2020-04-01 00:00:00 至 2020-04-03 00:00:00
select sysdate time from dual where to_char(sysdate,'yyyymmdd') between '20200402' and '20200402';
//02-APR-20,時間范圍是2020-04-02 00:00:00 至 2020-04-02 24:00:00 

2、將字符串轉化為日期再比較

select sysdate nowtime from dual where sysdate between to_date('20200401','yyyyMMdd') and to_date('20200403','yyyyMMdd');
//02-APR-20,時間范圍是2020-04-01 00:00:00 至 2020-04-03 00:00:00

注意:如果不在字符串中指定時間則轉換的時間默認為0點,所以前后日期一致則時間間隔為0。

select to_char(to_date('20200402','yyyyMMdd'),'yyyyMMdd hh24:mi:ss') nowtime from dual;
//20200402 00:00:00

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM