SQLServer中除数为零的处理技巧

一、利用case语句

当@b=0的时候,返回1

declare @a int;
declare @b int;
set @a=10
set @b=0
select case @b when 0 then 1 else @a/@b end

二、利用nullif函数

nullif函数有两个参数,定义如下:
NULLIF( expression , expression )
其作用就是:如果两个指定的表达式相等,就返回null值

看一示例:

select nullif(0,0)

运行结果:null

null与任何数进行任何运算,其结果都等于null,利用这点,我们可以将上面的sql改写为:

declare @a int;
declare @b int;
set @a=10
set @b=0
select @a/nullif(@b,0)

运行结果:null

再利用isnull函数,我们就可以实现当@b=0的时候,结果返回1的需求了。

isnull函数的定义如下:
isnull(参数1,参数2)
其作用就是,当参数1等于null时,就返回参数2的值

最终的sql改写如下:

declare @a int;
declare @b int;
set @a=10
set @b=0
select isnull(@a/nullif(@b,0),1)

 

 

参考:https://www.cnblogs.com/Nina-piaoye/p/5983480.html

posted @ 2020-03-02 09:07  ParanoiaApe  阅读(968)  评论(0)    收藏  举报