PL/SQL to_date日期判斷注意事項

to_date日期判斷注意事項

如果我們想找出2010年6月的RCV_TRANSACTIONS資料,可能會寫以下的SQL:

select * from rcv_transactions
  where creation_date >= to_date('20120601','yyyymmdd')
    and creation_date <= to_date('20120630','yyyymmdd');

可是執行的結果會找不到6/30日當天的資料,原因如下:
(10/1440表示10分鐘,因為一律以天來計算)

select (to_date('20120630','yyyymmdd')-10/1440) from dual;
結果:2012/6/29 下午 11:50:00
減了10分鐘,卻變成6/29日。

select (to_date('20120630 23:59','yyyymmdd hh24:mi')-10/1440) from dual;
結果:2012/6/30 下午 11:49:00

由上列兩個SQL可得知,to_date('20120630','yyyymmdd')的執行結果為2012/6/30 上午 00:00:00
,所以如果沒有加上指定時間的話,6/30日的資料是不會出現的。

所以6月份的資料判斷應該是:
select * from rcv_transactions
  where creation_date >= to_date('20120601 00:00','yyyymmdd hh24:mi')
    and creation_date <= to_date('20120630 23:59','yyyymmdd hh24:mi');

或者是
select * from rcv_transactions
  where creation_date >= to_date('20120601','yyyymmdd')
    and creation_date < to_date('20120701','yyyymmdd');

Windows 11安裝時跳過網路連線