SQL 遇到存储过程除以零错误。

SQL Stored Procedure Divide by zero error encountered.

试图弄清楚为什么我的存储过程给我一个 "divide by zero" 错误,我已经将它缩小到这个区域。如果我评论以下行,查询将成功运行。我不确定为什么。

            PartReceived.QuantityReceived / 
            (CASE 
                WHEN PurchaseOrderItem.QuantityOrdered IS NULL THEN PurchaseOrderItem.QuantityOrdered
                WHEN PurchaseOrderItem.QuantityOrdered = 0 THEN PurchaseOrderItem.QuantityOrdered
                ELSE PurchaseOrderItem.QuantityOrdered
            END) * 100.0 AS PercentageReceived

我确实在错误发生前收到此警告,但我已经完成了任何 google 搜索引导我做的大部分工作。我试过使用 IFNULL 而不是 IS NULL THEN 但这似乎也不起作用。

Warning: Null value is eliminated by an aggregate or other SET operation.

您可以使用 NULLIF():

避免被零除
        PartReceived.QuantityReceived / 
        NULLIF(CASE WHEN PurchaseOrderItem.QuantityOrdered IS NULL THEN PurchaseOrderItem.QuantityOrdered
                    WHEN PurchaseOrderItem.QuantityOrdered = 0 THEN PurchaseOrderItem.QuantityOrdered
                    ELSE PurchaseOrderItem.QuantityOrdered
                END), 0) * 100.0 AS PercentageReceived

这 return 的结果是 NULL 而不是生成错误。

实际上,您的逻辑更容易写成:

        (PartReceived.QuantityReceived / 
         NULLIF(PurchaseOrderItem.QuantityOrdered, 0)
        ) * 100.0 AS PercentageReceived

CASE 没有做任何事情。所有三个 THEN 子句 return 具有相同的值。