使用SQL计算当天距生日还有多少天的场景: 一开始使用的SQL写法如下
datediff(DAY,sysdate,to_date(year(sysdate)||substring('1988-07-10',5),'YYYY-MM-DD'))
但后面发现这种写法在遇到闰年的时候存在问题,如下面所示
>>select datediff(DAY,sysdate,to_date(year(sysdate)||substring('1988-07-10',5),'YYYY-MM-DD')) from dual;
(EXPR)
-----------
130
--- 1 row(s) selected.
>>select datediff(DAY,sysdate,to_date(year(sysdate)||substring('2020-02-29',5),'YYYY-MM-DD')) from dual;
*** ERROR[8415] The provided DATE, TIME, or TIMESTAMP is not valid and cannot be converted. Source data: 2022-02-29
--- 0 row(s) selected.
因而换了一种写法,将当前时间的年份修改为生日当年的年份,正确的写法如下:
select datediff(DAY,to_date(substring('2020-02-29',1,4)||substring(to_char(sysdate,'YYYY-MM-DD'),5),'YYYY-MM-DD'),to_date('2020-02-29','YYYY-MM-DD'))from dual;
样例输出为:
>>select datediff(DAY,to_date(substring('2020-02-29',1,4)||substring(to_char(sysdate,'YYYY-MM-DD'),5),'YYYY-MM-DD'),to_date('2020-02-29','YYYY-MM-DD'))from dual;
(EXPR)
-----------
-2
--- 1 row(s) selected.
>>select datediff(DAY,to_date(substring('1988-07-10',1,4)||substring(to_char(sysdate,'YYYY-MM-DD'),5),'YYYY-MM-DD'),to_date('1988-07-10','YYYY-MM-DD'))from dual;
(EXPR)
-----------
130
--- 1 row(s) selected.
|