NULL 值的数据库表更新错误
我有两张桌子。一个表实际上由日常事件填充,而另一个表只是另一个表的摘要。我有一个存储过程,可以删除每日表中存储的值。现在,每次删除后,汇总表也应更新,以便更新 SUM 减去删除的值。
我的问题是,当 Daily 表被清空时,自动求和会产生 NULL 值(因为在其中找不到任何条目)。然后应用程序崩溃,因为我的汇总表不应包含 NULL 值。
如果可能的话,如何创建一个过程,在 SUM 结果为 NULL 时使值变为 0?
示例查询:
DELETE FROM Daily WHERE DailyID = @DailyID
SELECT @TotalA = SUM(o.OutA), @TotalB = SUM(o.OutB), @TotalC = SUM(o.OutB)
FROM Daily
WHERE Day = @Day
UPDATE Summary
SET MyA = @TotalA, MyB = @TotalB, MyC = @TotalC
WHERE SummaryID = @SummaryID
根据上面给出的查询,假设我的每日表中总共有 10 个条目。 2 个是星期三条目,3 个是星期五条目,5 个是星期六条目。基本上,我的汇总表将包含三个条目 - 每个周三、周六和周五的汇总。
当我要求程序删除所有星期三条目时,将剩下 8 个条目(没有星期三)。因此,我必须更新我的摘要条目,表示所有星期三条目均已删除。但是,我不希望我的汇总表忘记他有一个星期三。因此,我希望他保留周三的条目,总汇总值为零 (0)。
I have a two tables. One table is actually populated by daily events while the other is just a summary of the other table. I have a stored procedure which deletes the values stored in the Daily Table. Now every after delete, the Summary table should also be updated such that the SUM will now be updated less the value of the one deleted.
My problem is when the Daily table has been emptied, then automatically summing it up yields a value of NULL (since no entries are found inside it). The application then crashes since my Summary Table should not contain NULL Values.
If it is possible, how can I create a procedure that would make the value 0 if the SUM results to NULL?
SAMPLE QUERY:
DELETE FROM Daily WHERE DailyID = @DailyID
SELECT @TotalA = SUM(o.OutA), @TotalB = SUM(o.OutB), @TotalC = SUM(o.OutB)
FROM Daily
WHERE Day = @Day
UPDATE Summary
SET MyA = @TotalA, MyB = @TotalB, MyC = @TotalC
WHERE SummaryID = @SummaryID
From my Query given above, let's say I have a total of 10 entries inside my Daily Table. 2 are Wednesday Entries, 3 are Friday, and 5 are Saturday Entries. So basically, my Summary Table will have three entries - a summary of each Wednesday, Saturday, and Friday.
When I ask my procedure to delete all the Wednesday Entries, then there will be 8 entries left (no wednesday). And so I have to update my Summary entry saying that all the wednesday entries have been deleted. However, I don't want my Summary Table to forget that he had a Wednesday. So instead, I want him to retain the Wednesday entry with Total Summary Values of zeroes (0).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是在 SQL Server 上尝试 ISNULL(SUM(Column),0) 吗?
Is this on SQL server try ISNULL(SUM(Column),0).
您可以使用
COALESCE
来替换NULL
按值:它采用参数列表,并返回第一个
NOT NULL
。编辑:根据您的示例,您可以执行类似的操作:
You can use
COALESCE
to replaceNULL
by a value:It takes a list of arguments, and returns the first one that is
NOT NULL
.EDIT: With your example you could do something like that: