我有这个错误信息:
Msg 8134,级别16,状态1,第1行,除以零错误。
写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?
我可以做以下任何一件事:
添加where子句,使除数永远不为零
Or
我可以添加一个case语句,这样就可以对0进行特殊处理。
使用NULLIF子句是最好的方法吗?
有没有更好的办法,或者如何实施?
我有这个错误信息:
Msg 8134,级别16,状态1,第1行,除以零错误。
写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?
我可以做以下任何一件事:
添加where子句,使除数永远不为零
Or
我可以添加一个case语句,这样就可以对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.
}
其他回答
使用NULLIF(exp,0),但以这种方式- NULLIF(ISNULL(exp,0),0)
如果exp为空,NULLIF(exp,0)将中断,但NULLIF(ISNULL(exp,0),0)将不会中断
为了避免“除零”错误,我们编写了这样的程序:
Select Case when divisor=0 then null
Else dividend / divisor
End ,,,
但这里有一种更好的方式:
Select dividend / NULLIF(divisor, 0) ...
现在唯一的问题是记住NullIf位,如果我使用“/”键。
这似乎是解决我的情况的最佳方法,当我试图解决除零的问题时,这种情况确实发生在我的数据中。
假设您想要计算各个学校俱乐部的男女比例,但是您发现下面的查询失败了,并且在试图计算指环王俱乐部的比例时出现了一个除零的错误,因为指环王俱乐部没有女性:
SELECT club_id, males, females, males/females AS ratio
FROM school_clubs;
可以使用NULLIF函数来避免除零。NULLIF比较两个表达式,如果相等则返回null,否则返回第一个表达式。
将查询重写为:
SELECT club_id, males, females, males/NULLIF(females, 0) AS ratio
FROM school_clubs;
任何数字除以NULL都会得到NULL,并且不会产生错误。
对于更新sql:
update Table1 set Col1 = Col2 / ISNULL(NULLIF(Col3,0),1)
添加一个CHECK约束,强制除数为非零 向表单添加验证器,以便用户不能在该字段中输入零值。