除以零时遇到错误,但应按 CASE 排除

Divide by zero error encountered, but should be excluded by CASE

我有以下代码,但出现错误:

Divide by zero error encountered.

SELECT
CASE WHEN SUM([monthly_qty]) = 0 THEN 999 
ELSE ROUND(SUM([monthly_buy] * ([monthly_markup]+100)/100),2) * SUM([monthly_qty] / [monthly_qty]) END as [monthly_total]
FROM [xxxxx].[dbo].[quote_items] WHERE docid='10152' 

导致错误的字段是第二个 [monthly_qty],就在 CASE 语句的 END 之前。

SUM([monthly_qty] / **[monthly_qty]**) 

monthly_qty 的值为零,所以错误是有道理的,但我很困惑,因为这个字段在 CASE 语句中,所以预期结果是 999

非常感谢任何帮助。

阅读 MS Docs,备注下有您的案例示例。

The CASE expression evaluates its conditions sequentially and stops with the first condition whose condition is satisfied. In some situations, an expression is evaluated before a CASE expression receives the results of the expression as its input. Errors in evaluating these expressions are possible. Aggregate expressions that appear in WHEN arguments to a CASE expression are evaluated first, then provided to the CASE expression. For example, the following query produces a divide by zero error when producing the value of the MAX aggregate. This occurs prior to evaluating the CASE expression.

我无法理解您代码中某些部分的原因,例如:

SUM([monthly_qty] / [monthly_qty])

当[monthly_qty] = 零时结果错误,非零时为1。

无论如何,当“monthly_qty”为零时,您可以设置一个默认值:

IIF([monthly_qty]= 0,'YOUR_DEFAULT_VALUE', [monthly_qty] / [monthly_qty])

然后:

SUM(IIF([monthly_qty]= 0,'YOUR_DEFAULT_VALUE', [monthly_qty] / [monthly_qty]))

原因很简单。此代码:

SUM([monthly_qty]) = 0

不阻止此代码中的除数为零:

SUM([monthly_qty] / [monthly_qty]) 

表达方式不同

最简单的解决方案(本质上是“标准”方法)是使用 NULLIF():

SUM([monthly_qty] / NULLIF([monthly_qty], 0)) 

不过,不知道你是不是真的打算:

SUM([monthly_qty]) / NULLIF(SUM([monthly_qty]), 0)