2011-09-19 89 views
0

我遇到了一些問題。我試圖獲取一個表來更新,但它沒有更新,因爲其中一個字段包含具有NULL值的行。無法將NULL值插入列

繼承人這給沒有錯誤的原始查詢:

 sql="UPDATE empPac SET quantityLimit = allocation, allocationStart = '"&allocationStart&"', nextUpdate = DATEADD(mm, allocationMonths, "&allocationStart&"), lastUpdate = GETDATE(), quantityIssued = 0, quantityShipped = 0 WHERE allocationMonths <> 0 AND nextUpdate <= DATEADD(mm, "&checkCondition&", GETDATE()) and empIdent in (select empIdent from employee where custIdent='"&custIdent&"')" 

現在,下次更新列可能爲空,所以我想以適應與此查詢:

 sql="UPDATE empPac SET quantityLimit = allocation, allocationStart = '"&allocationStart&"', nextUpdate = DATEADD(mm, allocationMonths, "&allocationStart&"), lastUpdate = GETDATE(), quantityIssued = 0, quantityShipped = 0 WHERE allocationMonths <> 0 AND (nextUpdate <= DATEADD(mm, "&checkCondition&", GETDATE()) OR nextUpdate IS NULL) and empIdent in (select empIdent from employee where custIdent='"&custIdent&"')" 

你可以請參閱括號中的「OR nextUpdate IS NULL」,以及nextUpdate的其他條件。

但是,我收到一個錯誤「無法將值NULL插入列'quantityLimit',表'myname.dbo.EmpPac';列不允許爲空,UPDATE失敗。

這對我來說沒有任何意義,因爲在查看myLittleAdmin時,會爲該表列中的某些行顯示NULL值。

+2

您應該真正參數化您的查詢http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html –

回答

1

OR nextUpdate IS NULL添加到您的WHERE子句將搜索條件擴大爲 - 即可找到更多行。

顯然,其中一個附加行在allocation字段中有一個NULL(然後根據錯誤消息將其分配給quantityLimit,它不是NULL)。

+0

真棒,我添加了「WHERE分配不爲空」,現在它的作品:)謝謝大家 – scarhand

2

這與NextUpdate列爲NULL無關,這與empPac表中的分配列爲NULL無關。處理分配列爲NULL(或修復數據),它會正常工作。

編輯:我可以用這個保證的唯一事情是錯誤就會消失:

sql="UPDATE empPac SET quantityLimit = allocation, allocationStart = '"&allocationStart&"', nextUpdate = DATEADD(mm, allocationMonths, "&allocationStart&"), lastUpdate = GETDATE(), quantityIssued = 0, quantityShipped = 0 WHERE allocationMonths <> 0 AND (nextUpdate <= DATEADD(mm, "&checkCondition&", GETDATE()) OR nextUpdate IS NULL) and empIdent in (select empIdent from employee where custIdent='"&custIdent&"') AND allocation IS NOT NULL" 
+0

但我沒有得到任何錯誤直到我添加到WHERE – scarhand

+1

因此,你的empPac表中無處分配NULL的地方?如果你這樣做了,那麼你的WHERE子句會導致具有NULL分配的行被選擇用於更新。再次指出分配列的位置爲NULL(通過將更新作爲SELECT運行,並添加一些列來幫助識別行)並處理該參數或修復數據。 – Wil

+0

編輯:看我的修復。它不能保證quantityLimit會被正確更新,但會阻止錯誤。 – Wil

2

問題不列nextUpdate;根據錯誤消息,問題是嘗試將NULL分配到quantityLimit列中。看着你的代碼,你正在設置quantityLimit等於值allocation,我認爲這是數據庫中的另一列 - 確保列或輸入不爲空。

+0

雖然第一個查詢工作正常。當我添加到WHERE中時發生問題...查看我的OP中的第一個查詢,它沒有提供任何錯誤...我在OP中發佈的第二個查詢確實如此。這就是爲什麼我輸了。 – scarhand

相關問題