我有一个错误出现“遇到除以零错误”。在 SQL Server 2005 中。我知道我有几行被零除,导致此错误。所以我想知道当除数为零时是否可以消除这个错误。如果除数为 0,它应该返回 0。我该怎么做?
sum(isnull(cast(S.S_AmountCollected as numeric(10, 2)), 0)) / sum(isnull(cast(S.AmountSold as numeric(10, 2)), 0))
谢谢!
我有一个错误出现“遇到除以零错误”。在 SQL Server 2005 中。我知道我有几行被零除,导致此错误。所以我想知道当除数为零时是否可以消除这个错误。如果除数为 0,它应该返回 0。我该怎么做?
sum(isnull(cast(S.S_AmountCollected as numeric(10, 2)), 0)) / sum(isnull(cast(S.AmountSold as numeric(10, 2)), 0))
谢谢!
使用 CASE 语句:
CASE WHEN SUM(ISNULL(CAST(S.AmountSold as numeric(10, 2)), 0) = 0
THEN 0
ELSE
SUM(ISNULL(CAST(S.S_AmountCollected as numeric(10, 2)), 0))
/
SUM(ISNULL(CAST(S.AmountSold as numeric(10, 2)), 0))
END
您无法消除此错误,因为整数除以 0 具有未定义的值。您必须添加显式检查才能获得您期望的行为。