人們經常遇到coalesce (接合)函式,而他們大都把它看做是isnull 的乙個更有效的形式。事實上,我發現它是非常有用的函式而卻只有很少的文件。在這篇文章裡,筆者將為你展示coalesce 的基本使用以及一些你可能從沒見過的特性。
讓我們首先從coalesce具有文件記錄的使用開始。根據msdn,coalesce返回它的引數中第乙個非空表示式。
例如,select coalesce(null, null, null, getdate())
它將返回當前的日期。它略過第乙個null值並返回第乙個非空的值。
對pivot(透視)使用coalesce
如果你對adventureworks資料庫執行下面的語句:
select name from humanresources.department
where (groupname = 'executive general and administration')
你將獲得像下面的乙個標準結果集。
圖1如果你想透視資料,你可以執行下面的命令。
declare @departmentname varchar(1000) select @departmentname = coalesce(@departmentname,'') + name + ';'
from humanresources.department
where (groupname = 'executive general and administration')
select @departmentname as departmentnames
並獲得下面的結果集。
圖2使用coalesce來執行多條sql語句
如果你可以使用coalesce語句來透視資料,那麼就可能通過透視資料和使用乙個分號來分隔這些操作從而執行多條sql語句。假設你想找到person schema
中任何欄位名稱為「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
下面是結果集。
圖3我個人喜歡能夠使用三行**殺掉資料庫中的所有事務。如果你曾經試過恢復資料庫而不能獲得專門的訪問,你就知道這是多麼有用的了。
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
這將得出乙個類似於下面的結果集。
COALESCE函式的用法
coalesce這個函式系統的用法如下 a.輸入引數為字元型別,且允許為空的,可以使用coalesce inputparameter,把null轉換成 b.輸入型別為整型,且允許為空的,可以使用coalesce inputparameter,0 把空轉換成0 c.輸入引數為字元型別,且是非空非空格的...
coalesce 函式詳解
coalesce 函式 返回列表中第乙個非null表示式的值。如果所有表示式求值為null,則返回null。coalesce expression 1,expression 2,expression n 依次參考各引數表示式,遇到非null值即停止並返回該值。如果所有的表示式都是空值,最終將返回乙個...
對html的全新認識
一 之前對於html的認知 2.html的所有標籤都是內建的,並且可以通過css進行樣式的修改。3.html是解釋型語言,不需要編譯,當我們部署到伺服器上,客戶端訪問的時候自己進行解析。4.html語言是w3c組織開發的 錯誤 5.html通過jsp達到動態網頁的效果 6.所有標籤都可以通過樣式指定...