我有这个错误信息:
Msg 8134,级别16,状态1,第1行,除以零错误。
写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?
我可以做以下任何一件事:
添加where子句,使除数永远不为零
Or
我可以添加一个case语句,这样就可以对0进行特殊处理。
使用NULLIF子句是最好的方法吗?
有没有更好的办法,或者如何实施?
我有这个错误信息:
Msg 8134,级别16,状态1,第1行,除以零错误。
写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?
我可以做以下任何一件事:
添加where子句,使除数永远不为零
Or
我可以添加一个case语句,这样就可以对0进行特殊处理。
使用NULLIF子句是最好的方法吗?
有没有更好的办法,或者如何实施?
当前回答
用零代替“除零”是有争议的,但这也不是唯一的选择。在某些情况下,用1代替是(合理的)合适的。我经常发现自己吸毒
ISNULL(Numerator/NULLIF(Divisor,0),1)
当我在看分数/计数的变化,并希望默认为1,如果我没有数据。例如
NewScore = OldScore * ISNULL(NewSampleScore/NULLIF(OldSampleScore,0),1)
通常情况下,我实际上在其他地方计算过这个比率(尤其是因为它可以为低分母提供一些非常大的调整因素)。在这种情况下,我通常控制OldSampleScore大于阈值;这就排除了零的可能性。但有时“hack”是合适的。
其他回答
如果你想返回零,如果发生零分割,你可以使用:
SELECT COALESCE(dividend / NULLIF(divisor,0), 0) FROM sometable
对于每一个为0的除数,结果集中都会得到一个0。
对于更新sql:
update Table1 set Col1 = Col2 / ISNULL(NULLIF(Col3,0),1)
为了避免“除零”错误,我们编写了这样的程序:
Select Case when divisor=0 then null
Else dividend / divisor
End ,,,
但这里有一种更好的方式:
Select dividend / NULLIF(divisor, 0) ...
现在唯一的问题是记住NullIf位,如果我使用“/”键。
当错误传播回调用程序时,可以适当地处理它(如果需要,可以忽略它)。在c#中,SQL中发生的任何错误都会抛出一个异常,我可以捕获并在我的代码中处理,就像任何其他错误一样。
I agree with Beska in that you do not want to hide the error. You may not be dealing with a nuclear reactor but hiding errors in general is bad programming practice. This is one of the reasons most modern programming languages implement structured exception handling to decouple the actual return value with an error / status code. This is especially true when you are doing math. The biggest problem is that you cannot distinguish between a correctly computed 0 being returned or a 0 as the result of an error. Instead any value returned is the computed value and if anything goes wrong an exception is thrown. This will of course differ depending on how you are accessing the database and what language you are using but you should always be able to get an error message that you can deal with.
try
{
Database.ComputePercentage();
}
catch (SqlException e)
{
// now you can handle the exception or at least log that the exception was thrown if you choose not to handle it
// Exception Details: System.Data.SqlClient.SqlException: Divide by zero error encountered.
}
你至少可以阻止查询被错误打断,如果有被0除,返回NULL:
SELECT a / NULLIF(b, 0) FROM t
然而,我永远不会像其他得到很多赞的答案那样,用合并将其转换为零。从数学意义上讲,这是完全错误的,甚至是危险的,因为您的应用程序可能会返回错误和误导性的结果。