我有这个错误信息:
Msg 8134,级别16,状态1,第1行,除以零错误。
写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?
我可以做以下任何一件事:
添加where子句,使除数永远不为零
Or
我可以添加一个case语句,这样就可以对0进行特殊处理。
使用NULLIF子句是最好的方法吗?
有没有更好的办法,或者如何实施?
我有这个错误信息:
Msg 8134,级别16,状态1,第1行,除以零错误。
写SQL代码的最好方法是什么,这样我就再也不会看到这个错误消息了?
我可以做以下任何一件事:
添加where子句,使除数永远不为零
Or
我可以添加一个case语句,这样就可以对0进行特殊处理。
使用NULLIF子句是最好的方法吗?
有没有更好的办法,或者如何实施?
当前回答
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除,返回NULL:
SELECT a / NULLIF(b, 0) FROM t
然而,我永远不会像其他得到很多赞的答案那样,用合并将其转换为零。从数学意义上讲,这是完全错误的,甚至是危险的,因为您的应用程序可能会返回错误和误导性的结果。
SELECT Dividend / ISNULL(NULLIF(Divisor,0), 1) AS Result from table
通过使用nullif()捕获零,然后使用isnull()捕获结果为零,可以避免除零错误。
使用NULLIF(exp,0),但以这种方式- NULLIF(ISNULL(exp,0),0)
如果exp为空,NULLIF(exp,0)将中断,但NULLIF(ISNULL(exp,0),0)将不会中断
我写了一个函数来处理我的存储过程:
print 'Creating safeDivide Stored Proc ...'
go
if exists (select * from dbo.sysobjects where name = 'safeDivide') drop function safeDivide;
go
create function dbo.safeDivide( @Numerator decimal(38,19), @divisor decimal(39,19))
returns decimal(38,19)
begin
-- **************************************************************************
-- Procedure: safeDivide()
-- Author: Ron Savage, Central, ex: 1282
-- Date: 06/22/2004
--
-- Description:
-- This function divides the first argument by the second argument after
-- checking for NULL or 0 divisors to avoid "divide by zero" errors.
-- Change History:
--
-- Date Init. Description
-- 05/14/2009 RS Updated to handle really freaking big numbers, just in
-- case. :-)
-- 05/14/2009 RS Updated to handle negative divisors.
-- **************************************************************************
declare @p_product decimal(38,19);
select @p_product = null;
if ( @divisor is not null and @divisor <> 0 and @Numerator is not null )
select @p_product = @Numerator / @divisor;
return(@p_product)
end
go
使用where子句过滤数据,这样就不会得到0值。