我有这个错误信息:

Msg 8134,级别16,状态1,第1行,除以零错误。

写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?

我可以做以下任何一件事:

添加where子句,使除数永远不为零

Or

我可以添加一个case语句,这样就可以对0进行特殊处理。

使用NULLIF子句是最好的方法吗?

有没有更好的办法,或者如何实施?


当前回答

SELECT Dividend / ISNULL(NULLIF(Divisor,0), 1) AS Result from table

通过使用nullif()捕获零,然后使用isnull()捕获结果为零,可以避免除零错误。

其他回答

在这种情况下,你可以除以0。商业规则是计算库存周转,你用一段时间内的销售成本,按年计算。在你得到年化数字之后,你要除以该时期的平均库存。

I'm looking at calculating the number of inventory turns that occur in a three month period. I have calculated that I have Cost of Goods sold during the three month period of $1,000. The annual rate of sales is $4,000 ($1,000/3)*12. The beginning inventory is 0. The ending inventory is 0. My average inventory is now 0. I have sales of $4000 per year, and no inventory. This yields an infinite number of turns. This means that all my inventory is being converted and purchased by customers.

这是关于如何计算库存周转的业务规则。

There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html

有时,0可能不合适,但有时1也不合适。有时,从0到100,000,000的跳跃被描述为1%或100%的变化也可能是误导性的。在这种情况下,100,000,000 %可能是合适的。这取决于你打算根据百分比或比率得出什么样的结论。

例如,一个非常小的销售项目从2-4个销量变化,而一个非常大的销售项目从1,000,000个销量变化到2,000,000个销量变化,对分析师或管理层来说可能意味着非常不同的东西,但都是100%或1个变化。

隔离NULL值可能比在一堆混合了合法数据的0%或100%行中搜索要容易得多。通常,分母中的0可能表示错误或缺少值,您可能不想只是为了使数据集看起来整洁而填充任意值。

CASE
     WHEN [Denominator] = 0
     THEN NULL --or any value or sub case
     ELSE [Numerator]/[Denominator]
END as DivisionProblem

我是这样解决的:

IIF(ValueA != 0, Total / ValueA, 0)

它可以被包装在一个更新中:

SET Pct = IIF(ValueA != 0, Total / ValueA, 0)

或者在选择中:

SELECT IIF(ValueA != 0, Total / ValueA, 0) AS Pct FROM Tablename;

想法吗?

用零代替“除零”是有争议的,但这也不是唯一的选择。在某些情况下,用1代替是(合理的)合适的。我经常发现自己吸毒

 ISNULL(Numerator/NULLIF(Divisor,0),1)

当我在看分数/计数的变化,并希望默认为1,如果我没有数据。例如

NewScore = OldScore *  ISNULL(NewSampleScore/NULLIF(OldSampleScore,0),1) 

通常情况下,我实际上在其他地方计算过这个比率(尤其是因为它可以为低分母提供一些非常大的调整因素)。在这种情况下,我通常控制OldSampleScore大于阈值;这就排除了零的可能性。但有时“hack”是合适的。