我有这个错误信息:

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

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

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

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

Or

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

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

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


当前回答

在这种情况下,你可以除以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.

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

其他回答

对于更新sql:

update Table1 set Col1 = Col2 / ISNULL(NULLIF(Col3,0),1)
SELECT Dividend / ISNULL(NULLIF(Divisor,0), 1) AS Result from table

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

为了避免“除零”错误,我们编写了这样的程序:

Select Case when divisor=0 then null
Else dividend / divisor
End ,,,

但这里有一种更好的方式:

Select dividend / NULLIF(divisor, 0) ...

现在唯一的问题是记住NullIf位,如果我使用“/”键。

你至少可以阻止查询被错误打断,如果有被0除,返回NULL:

SELECT a / NULLIF(b, 0) FROM t 

然而,我永远不会像其他得到很多赞的答案那样,用合并将其转换为零。从数学意义上讲,这是完全错误的,甚至是危险的,因为您的应用程序可能会返回错误和误导性的结果。

使用where子句过滤数据,这样就不会得到0值。