安全的INTERVAL算法

zer*_*kms 3 oracle oracle11g oracle11gr2

此查询适用于所有错误

select add_months(date '2011-01-31', 1) from dual;
Run Code Online (Sandbox Code Playgroud)

,而这一个:

select date '2011-01-31' + interval '1' month from dual;
Run Code Online (Sandbox Code Playgroud)

回报

ORA-01839: date not valid for month specified
Run Code Online (Sandbox Code Playgroud)

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

Nul*_*ion 5

这遵循ANSI指定的向日期添加s的行为1INTERVAL.这也记录在这里:

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

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.
Run Code Online (Sandbox Code Playgroud)