SQL Server(避免除以空值)

时间:2014-10-09 13:01:28

标签: sql sql-server

我有以下查询:

UPDATE FinanceTable
SET    PercentageComplete = (SELECT ( Sum(LabourFinance.HoursTaken / LabourFinance.Hours) / Count(LabourID) )
                             FROM   LabourFinance
                             WHERE  FinanceID = (SELECT TOP 1 FinanceID
                                                 FROM   FinanceTable
                                                 ORDER  BY changedate DESC)
                             GROUP  BY FinanceID)
WHERE  FinanceID = (SELECT TOP 1 FinanceID
                    FROM   FinanceTable 
                    ORDER  BY changedate DESC)

此查询的作用是根据更改的内容选择1个特定单元格,我使用它来更新FinanceTable中的成本值。

这种情况导致了我的问题:

  • 我已拨出100小时完成任务
  • HoursTaken在插入表格后目前为0,因为尚未开始
  • 在计算PercntageComplete时,SQL Server不允许我这样做(0/100),因此导致错误......

我该如何防止这种情况?我期望的结果将是PercentageComplete = 0%

感谢任何输入:)下面是我通过runnig上面的查询获得的错误消息

enter image description here

1 个答案:

答案 0 :(得分:2)

参考此

How to avoid the “divide by zero” error in SQL?

UPDATE FinanceTable
SET    PercentageComplete = (SELECT COALESCE (Sum(COALESCE (LabourFinance.HoursTaken / NULLIF(LabourFinance.Hours, 0), 0)) / NULLIF(Count(LabourID), 0), 0)
                             FROM   LabourFinance
                             WHERE  FinanceID = (SELECT TOP 1 FinanceID
                                                 FROM   FinanceTable
                                                 ORDER  BY changedate DESC)
                             GROUP  BY FinanceID)
WHERE  FinanceID = (SELECT TOP 1 FinanceID
                    FROM   FinanceTable
                    ORDER  BY changedate DESC)