2011-09-19 93 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

相关问题