分頁實現方法的效能比較_應用技巧

來源:互聯網
上載者:User
幾種常用預存程序分頁方法
TopN方法
select Top(@PageSize) from TableName where ID Not IN
(Select Top ((@PageIndex-1)*@PageSize) ID from Table Name where .... order by ... )
where .... order by ...
暫存資料表
複製代碼 代碼如下:

declare @indextable table(id int identity(1,1),nid int,PostUserName nvarchar(50))
declare @PageLowerBound int
declare @PageUpperBound int
set @PageLowerBound=(@pageindex-1)*@pagesize--下限
set @PageUpperBound=@PageLowerBound+@pagesize--上限
set rowcount @PageUpperBound
insert into @indextable(nid,PostUserName) select ReplyID,PostUserName from TableName order by ......
select * from TableName p,@indextable t where p.ID=t.nid
and t.id>@PageLowerBound and t.id<=@PageUpperBound order by t.id

CTE--2005新文法,類似暫存資料表,但是生命週期稍微不同,這裡只是他的一個運用
with cte_temp--定義零時表,PageIndex是一個計算欄位,儲存了搜尋結果的頁號
As (ceiling((Row_Number() over(order by .... )-1)/@pagesize as int) as PageIndex,* from TableName where.....)
select * from cte_temp where pageindex=@pageindex-1;
結論:
TopN在小頁數下最快,如果在10頁以下,可以考慮用它,CTE和暫存資料表時間很穩定,CTE消耗的時間比暫存資料表多,但是不會引起tempdb的暴漲和IO增加
效能比較
實驗環境:win2003server,Sqlserver2005,庫大小2,567,245行,沒有where子句,實驗時每頁大小50,頁碼作為變數
取0,3,10,31,100,316,1000,3162...頁,也就是10的指數,實驗結果如下
頁數 TopN CTE 暫存資料表(有緩衝) 暫存資料表(無緩衝)
公司正在使用的預存程序 CTE改進
1 3 12 10 101 457 7302
3 15 7 79 5524 464 7191
10 127 5504 88 3801 464 6116
32 588 9672 122 3601 976 7602
100 4680 9738 166 4235 486 7151
316 45271 9764 323 3867 522 7255
1000 Null 9806 869 2578 635 8948
3162 Null 9822 2485 4110 12460 8210
10000 Null 9754 7812 11926 14250 7359
31623 Null 9775 18729 33218 15249 7511
100000 Null Null 31538 55569 17139 6124
資料解釋和分析
暫存資料表分為有沒有緩衝兩種時間,CTE就是上面的方法,CTE改進只是把選入CTE暫存資料表的列數減少了,只選取了頁號和主鍵,Null表示時間無法計算(時間太長),資料單位是毫秒.
從上面的資料可以看到,TopN在前32頁都是有優勢的,但是頁數增大後,效能降低很快,CTE改進比CTE有所進步,平均進步兩秒左右,但是還是比暫存資料表慢,但是考慮暫存資料表會增大記錄檔的大小,引起大量IO,CTE也就有他自己的優勢,公司現在正在使用的預存程序效率不錯,但是在頁碼靠後的情況下效能會降低

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.