转自:http://www.maomao365.com/?p=4390

一、coalesce函数简介


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


select isnull(@a,isnull(@b,isnull(@c,null)))
/*当需判断的参数越多时,我们的函数表达式就会变的异常复杂*/

但我们使用coalesce函数,会使此 表达式变的优美,通俗易懂
select coalesce(@a,@b,@c)
——————————————————————————–



二、coalesce 应用举例

 

  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)
 

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!