但我们使用coalesce函数,会使此 表达式变的优美,通俗易懂
select coalesce(@a,@b,@c)
——————————————————————————–
NULLIF( expression , expression )
转自:http://www.maomao365.com/?p=4390
declare @a int;
二、coalesce 应用举例
我们知道,null与任何数进行任何运算,其结果都等于null,利用这点,我们可以将上面的sql改写为:
一、coalesce函数简介
set @b=0
declare @a varchar(10),@b varchar(10),@c varchar(10),@d int
select coalesce(@a,@b,@c)
set @a ='g'
select coalesce(@a,@b,@c)
set @a =null
set @b ='g2'
set @c ='g3'
select coalesce(@a,@b,@c)
set @a =null
set @b =null
set @c =null
set @d =100
select coalesce(@a,@b,@c,@d)
运行结果:null
select isnull(@a,isnull(@b,isnull(@c,null)))
/*当需判断的参数越多时,我们的函数表达式就会变的异常复杂*/
select @a/nullif(@b,0)
declare @b int;
(如果有朋友对isnull函数不了解的话,这里可以解释一下。
coalesce 系统函数,比ISNULL更强大,更方便的系统函数,
coalesce可以接收多个参数,返回最左边不为NULL的参数,当所有参数都为空时,则返回NULL
coalesce是最优isnull写法解决方案
以前我们使用isnull对两列或多列数据进行为空返回时候,需要多次使用isnull函数
—————————————————————————-
例:
declare @a varchar(10),@b varchar(10),@c varchar(10)
当@a为null时,我们查看@b是否为NULL,不为null,则返回@b ,否则查看@c
不为NULL,则返回@c ,否则返回NULL
nullif函数有两个参数,定义如下:
再利用isnull函数,我们就可以实现当@b=0的时候,结果返回1的需求了。最终的sql改写如下:
select nullif(0,0)
其运行结果自然为null了。
利用nullif函数。
本文由美高梅官方网站发布于数据统计,转载请注明出处:MSSQL coalesce系统函数简介