ADD_MONTHS() 如果第二個引數是小數會怎麼樣?
阿新 • • 發佈:2019-01-28
我們經常使用ADD_MONTHS()函式來獲取一個日期的幾個月之後的日期,例如,我們希望得到兩個月之後的日期(2013年04月05日):
ChenZw> alter session set nls_date_format = 'yyyy-mm-dd';
會話已更改。
已用時間: 00: 00: 00.00
ChenZw> select add_months(to_date('20130405','yyyymmdd'),2) from dual;
ADD_MONTHS
----------
2013-06-05
已選擇 1 行。
已用時間: 00: 00: 00.00
上面的例子中,我們得到了2013年04月05日後面第二個月的該日期,也就是2013年06月05日,這個是符合我們期望的日期。
但是這裡有一個問題,如果我想得到,該日期(2013年04月05日)之後的1.2個月的日期呢?讓我們看一下:
ChenZw> select add_months(to_date('20130405','yyyymmdd'),1.2) from dual;
ADD_MONTHS
----------
2013-05-05
已選擇 1 行。
已用時間: 00: 00: 00.00
咦? 這個答案好像不是我想要的,我希望的應該是1.2個月之後的啊!能不能不要這麼不嚴謹!你應該是給我四捨五入了吧?那就告訴我1.9999999999999個月的今天是幾號吧!
ChenZw> select add_months(to_date('20130405','yyyymmdd'),1.9999999999999) from dual;
ADD_MONTHS
----------
2013-05-05
已選擇 1 行。
已用時間: 00: 00: 00.00
看到這個答案,我有點無語哽咽了,幸虧沒有在工作中使用啊,否則我就悲劇了,日期很有可能就算錯了。Oracle,你能不能不這麼坑爹。
帶著疑惑的心情,去請教Oracle的官方文件:
ADD_MONTHS
Syntax
Purpose
ADD_MONTHS
returns the date date
plus integer
months.
A month is defined by the session parameter NLS_CALENDAR
. The date argument can be a datetime value or any value that can be implicitly converted to DATE
. The integer
argument
can be an integer or any value that can be implicitly converted to an integer. The return type is always DATE
, regardless
of the data type of date
. If date
is
the last day of the month or if the resulting month has fewer days than the day component of date
, then
the result is the last day of the resulting month. Otherwise, the result has the same day component as date
.
Examples
The following example returns the month after the hire_date
in the sample table employees
:
SELECT TO_CHAR(ADD_MONTHS(hire_date, 1), 'DD-MON-YYYY') "Next month" FROM employees WHERE last_name = 'Baer'; Next Month ----------- 07-JUL-2002現在明白了,原來1.9999999999999是被直接擷取成1了,Oracle所謂的implicitly convert是截掉小數點之後的部分。 作者 陳字文(熱衷於PM\ORACLE\JAVA等,歡迎同行交流):ziwen#163.com 扣扣:4零9零2零1零零