3

此查询适用于我们的错误

select add_months(date '2011-01-31', 1) from dual;

,而这个:

select date '2011-01-31' + interval '1' month from dual;

返回

ORA-01839: date not valid for month specified

那么有没有任何安全的方法来使用INTERVAL文字添加间隔?

4

1 回答 1

5

这遵循 ANSI 指定的将s 添加到日期的行为1 。INTERVAL这也记录在这里

当间隔计算返回日期时间值时,结果必须是实际的日期时间值,否则数据库会返回错误。例如,接下来的两个语句返回错误:

SELECT TO_DATE('31-AUG-2004','DD-MON-YYYY') + TO_YMINTERVAL('0-1') FROM DUAL;

SELECT TO_DATE('29-FEB-2004','DD-MON-YYYY') + TO_YMINTERVAL('1-0') FROM DUAL;

ADD_MONTHS另一方面,如果结果月份的天数较少,该函数只会为您提供该月的最后一天 - 我相信创建此函数是为了解决这个问题。


1 http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

b) Arithmetic is performed so as to maintain the integrity of
  the datetime data type that is the result of the <datetime
  value expression>. This may involve carry from or to the
  immediately next more significant <datetime field>. If the
  data type of the <datetime value expression> is TIME, then
  arithmetic on the HOUR <datetime field> is undertaken modulo
  24. If the <interval value expression> or <interval term> is
  a year-month interval, then the DAY field of the result is
  the same as the DAY field of the <datetime term> or <datetime
  value expression>.

c) If, after the preceding step, any <datetime field> of the
  result is outside the permissible range of values for the
  field or the result is invalid based on the natural rules for
  dates and times, then an exception condition is raised: data
  exception-datetime field overflow.
于 2011-09-01T06:40:15.970 回答