安全的INTERVAL算法

时间:2011-09-01 06:19:26

标签: oracle oracle11g oracle11gr2

此查询无误地运行

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文字添加间隔的安全方法?

1 个答案:

答案 0 :(得分:5)

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

  

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

     

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.