我在 Oracle 数据库 10g 上有以下查询:
SELECT (CURRENT_DATE - INTERVAL '1' YEAR) FROM DUAL;
它运行正常,但今天我收到此错误:
ORA-01839: date not valid for month specified
01839. 00000 - "date not valid for month specified"
*Cause:
*Action:
我知道如何避免此类错误,但我的问题是为什么会抛出该错误?
最佳答案
这是预期的行为;请参阅第六个项目符号 in the datetime/interval arithmetic section文档。
When interval calculations return a datetime value, the result must be an actual datetime value or the database returns an error. For example, the next two statements return errors:
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;
The first fails because adding one month to a 31-day month would result in September 31, which is not a valid date. The second fails because adding one year to a date that exists only every four years is not valid. However, the next statement succeeds, because adding four years to a February 29 date is valid:
SELECT TO_DATE('29-FEB-2004', 'DD-MON-YYYY') + TO_YMINTERVAL('4-0') FROM DUAL; TO_DATE(' --------- 29-FEB-08
您可以使用add_months
,它具有相反的行为 - 有时也会引起困惑。您需要决定哪一个最适合您。
关于oracle - 为什么当我从当前日期减去一年时出现 Oracle 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9495905/