iT邦幫忙

DAY 8
4

MS SQL Server新特性探險:探險代碼 Denali系列 第 8

[Denali 新特性探險8]Rows and Range

這篇介紹 Rows and Range。
Rows and Range:允許更改分區中的開始位置和結束位置。
注意事項:
1.並非所有function 都支援 rows and range
2.使用 rows and range必須指定 order by
3.有指定 order by但未使用rows and range,
則預設為 range between undounded preceding and current rows。

設定開始位置和結束位置五種方式

示範

select c1,c2,sum(c2) over (order by c1 range unbounded preceding) as '累加D量1',
sum(c2) over (order by c1 range between unbounded preceding AND unbounded following) as '累加量2',
sum(c2) over (order by c1 rows between current row and 1 following ) as '累加量3',
sum(c2) over (order by c1 rows 1 preceding ) as '累加量4',
sum(c2) over (order by c1 rows between 1 preceding and 3 following  ) as '累加量5'
from dbo.mysales

假設今天我們有計算累加值 需求(如下圖)。

這裡我將測試 Denali 和 SQL2005/SQL2008 兩種寫法上的效能差異。

原始資料

Denali 寫法

declare @starttime time(7),@endtime time(7),@elaspedtime numeric(20,7);
set @starttime=GETDATE() ;
--range unbounded preceding
select c1,c2, sum(c2) over (order by c1 range unbounded preceding) as '累加量'
from dbo.mysales 
set @endtime=GETDATE(); 
set @elaspedtime = convert(integer, datediff(ms, @starttime, @endtime));
select @elaspedtime as '花費時間(ms)' 


花費時間和查詢結果。


執行計畫總成本。

SQL2005/2008 寫法

declare @result table(c1 varchar(10),c2 int,total int default(0))
declare @starttime time(7),@endtime time(7),@elaspedtime numeric(20,7);
set @starttime=GETDATE() ;
--將來源資料塞結果表
insert into @result select *,0 from dbo.mysales
declare @total int
set @total=0
update @result
--設定變數與資料行相同的值
set @total = total = @total + c2
--結果
select t1.c1,t1.c2,t1.total as '累加量' 
from @result t1  
set @endtime=GETDATE(); 
set @elaspedtime = convert(integer, datediff(ms, @starttime, @endtime));
select @elaspedtime as '花費時間(ms)' 


花費時間和查詢結果。




執行計畫總成本。

一起比較兩者執行計畫成本(將可更明顯看出差異)。

--Denali 
select c1,c2, sum(c2) over (order by c1 range unbounded preceding) as '累加量'
from dbo.mysales 
--2005/2008 
declare @result table(c1 varchar(10),c2 int,total int default(0))
--將來源資料塞結果表
insert into @result select *,0 from dbo.mysales
declare @total int
set @total=0
update @result
--設定變數與資料行相同的值
set @total = total = @total + c2
--結果
select t1.c1,t1.c2,t1.total as '累加量' 
from @result t1  

效能比較結果表

針對計算累加值需求, Denali 寫法很明顯優於SQL2005/2008 ,
當然Rows and Range 應用不只這些,其餘應用大家有興趣可自行玩玩看。

MS SQL Server新特性探險:探險代碼 Denali 全系列文章


上一篇
[Denali 新特性探險7]Paging Implementation
下一篇
[Denali 新特性探險9]With Result Sets
系列文
MS SQL Server新特性探險:探險代碼 Denali30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言