Сейф ИНТЕРВАЛ арифметика - PullRequest
       7

Сейф ИНТЕРВАЛ арифметика

3 голосов
/ 01 сентября 2011

Этот запрос работает с нашими ошибками

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 Ответ

5 голосов
/ 01 сентября 2011

Это соответствует ANSI-определенному поведению 1 добавления INTERVAL s к датам. Это также задокументировано здесь :

Когда интервальные вычисления возвращают значение 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.
...