2011-09-01 48 views
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文本添加間隔任何安全方法?

+0

@NullUserException:是的,這很有趣,謝謝 – zerkms

回答

5

這遵循ANSI指定的行爲將日期添加INTERVAL s。這也證明here

當間隔計算返回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將只是給你這個月的最後一天,如果得到的一個月少天 - 我相信這個功能是爲了解決這個問題而創建的。


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.