2011-12-31 83 views
0

我有一個問題,這個運行的Oracle SQL語句時:日期無效月指定

SELECT * 
    FROM tbl_content 
WHERE last_updated >= (systimestamp - INTERVAL '1' month(1)) 
ORDER BY last_updated desc 

而這個錯誤:

java.sql.SQLException: ORA-01839: date not valid for month specified 

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111) 
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:330) 
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:287) 
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:742) 
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:212) 
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:951) 
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1053) 
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:835) 
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1123) 
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3284) 
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3328) 
    at com.vtdd.sms.content.xskt.XsktService.getKQXSFollowArea(XsktService.java:4044) 
    at com.vtdd.sms.content.xskt.XsktService.getMessages(XsktService.java:421) 
    at com.vht.sms.content.ContentAbstract.getSubmitMessages(ContentAbstract.java:47) 
    at com.vht.sms.content.ContentFactory.getSubmitMessages(ContentFactory.java:335) 
    at com.vht.sms.content.ContentFactory.run(ContentFactory.java:62) 
    at java.lang.Thread.run(Thread.java:662) 

你能告訴我什麼是錯?

回答

7

首先,你爲什麼使用systimestamp?如果你想這個月,那麼肯定sysdate是不夠確切的?其次,我喜歡 - 也就是個人喜好 - 非常清楚發生了什麼。 Oracle有一個add_months函數,它可以做你想做的。所以,你的查詢可以很容易地:

SELECT * 
    FROM tbl_content 
WHERE last_updated >= add_months(sysdate, -1) 
ORDER BY last_updated desc 
+0

非常感謝你@Ben – user1024858 2011-12-31 13:15:29

4

什麼其實是錯誤的是interval arithmetic不調整天 - 見第6子彈鏈接:

When interval calculations return a datetime value, the result must be an actual datetime value or the database returns an error.

ADD_MONTHS做;作爲鏈接說:

If date is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month.

所以,ADD_MONTHS(DATE '2011-12-31', -1)給你2011-11-30,同時DATE '2011-12-31' - INTERVAL '1' MONTH試圖給你2011年11月31日,這是有消息稱,是不是有效的日期。如果這種行爲實際上是錯誤的,這是出乎意料的,但我相信它符合ANSI。可能有些時候你希望它以這種方式工作,儘管我想不出任何...)

相關問題