欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL Server COALESCE函数详解及实例

程序员文章站 2024-02-11 17:42:28
sql server coalesce函数详解 很多人知道isnull函数,但是很少人知道coalesce函数,人们会无意中使用到coalesce函数,并且发现它比isn...

sql server coalesce函数详解

很多人知道isnull函数,但是很少人知道coalesce函数,人们会无意中使用到coalesce函数,并且发现它比isnull更加强大,其实到目前为止,这个函数的确非常有用,本文主要讲解其中的一些基本使用:

  首先看看联机丛书的简要定义:

 返回其参数中第一个非空表达式语法: 

coalesce ( expression [ ,...n ] ) 

如果所有参数均为 null,则 coalesce 返回 null。至少应有一个 null 值为 null 类型。尽管 isnull 等同于 coalesce,但它们的行为是不同的。包含具有非空参数的 isnull 的表达式将视为 not null,而包含具有非空参数的 coalesce 的表达式将视为 null。在 sql server 中,若要对包含具有非空参数的 coalesce 的表达式创建索引,可以使用 persisted 列属性将计算列持久化,如以下语句所示:

create table #checksumtest  
   ( 
     id int identity , 
     num int default ( rand() * 100 ) , 
     rowchecksum as coalesce( checksum( id , num ) , 0 ) persisted primary key 
   ); 

 下面来看几个比较有用的例子:
首先,从msdn上看看这个函数的使用方法,coalesce函数(下面简称函数),返回一个参数中非空的值。如:

select coalesce(null, null, getdate()) 

由于两个参数都为null,所以返回getdate()函数的值,也就是当前时间。即返回第一个非空的值。由于这个函数是返回第一个非空的值,所以参数里面必须最少有一个非空的值,如果使用下面的查询,将会报错:

select coalesce(null, null, null) 


然后来看看把函数应用到pivot中,下面语句在adventureworks 数据库上运行:

select name 
 from  humanresources.department 
 where  ( groupname= 'executive generaland administration' ) 

会得到下面的结果:

SQL Server COALESCE函数详解及实例

如果想扭转结果,可以使用下面的语句:

declare @departmentname varchar(1000) 
  
 select @departmentname = coalesce(@departmentname, '') + name + ';' 
 from  humanresources.department 
 where  ( groupname= 'executive generaland administration' ) 
  
 select @departmentname as departmentnames 

SQL Server COALESCE函数详解及实例使用函数来执行多条sql命令:

当你知道这个函数可以进行扭转之后,你也应该知道它可以运行多条sql命令。并且使用分号来区分独立的操作。下面语句是在person架构下,有名字为name的列的值:

declare @sql varchar(max)  
  
 create table #tmp  
  (clmn varchar(500),  
   val varchar(50))  
  
 select @sql=coalesce(@sql,'')+cast('insert into #tmp select ''' + table_schema + '.' + table_name + '.'  
 + column_name + ''' as clmn, name from ' + table_schema + '.[' + table_name +  
 '];' as varchar(max))  
 from information_schema.columns  
 join sysobjects b on information_schema.columns.table_name = b.name  
 where column_name = 'name'  
  and xtype = 'u'  
  and table_schema = 'person'  
  
 print @sql  
 exec(@sql)  
  
 select * from #tmp  
 drop table #tmp 


SQL Server COALESCE函数详解及实例

还有一个很重要的功能:。当你尝试还原一个库,并发现不能独占访问时,这个功能非常有效。我们来打开多个窗口,来模拟一下多个连接。然后执行下面的脚本:

declare @sql varchar(8000) 
  
 select @sql = coalesce(@sql, '') + 'kill ' + cast(spid as varchar(10)) + '; ' 
 from  sys.sysprocesses 
 where  dbid = db_id('adventureworks') 
  
 print @sql --exec(@sql) replace the print statement with exec to execute 

结果如下:

SQL Server COALESCE函数详解及实例

然后你可以把结果复制出来,然后一次性杀掉所有session。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!