SQL存储过程遇到零错误。

时间:2015-11-09 16:59:17

标签: sql sql-server stored-procedures 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

我确实在错误发出之前收到了此警告,但我已经完成了谷歌搜索引导我做的很多事情。我尝试使用IFNULL而不是IS NULL那么,但这似乎也没有用。

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

1 个答案:

答案 0 :(得分:2)

您可以使用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

这会将结果返回为NULL,而不是生成错误。

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

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

CASE没有做任何事情。所有三个THEN子句都返回相同的值。