給大家分享個效率最高的分頁查詢 5000萬級別有效 比 ROWNUMBER 和Top效率高
代碼如下:
/*
日期:2009-03-19
功能:根據(jù)各種條件獲取 游戲國家任務(wù) 列表數(shù)據(jù)
*/
Create procedure [dbo].[PrGs_Nation_Task_GetList]
@PageSize int = 100, — 每頁顯示記錄條數(shù),默認為100
@PageIndex int = 1, — 當(dāng)前提取要顯示的頁碼,默認為1,數(shù)據(jù)庫根據(jù)PageSize,PageIndex 計算返回一頁數(shù)據(jù)
@RetTotal int output, — 記錄總數(shù)
@RetCount int output, — 返回記錄數(shù)
@RetPageIndex int output, — 輸出當(dāng)前頁碼
@ReturnDesc varchar(128) output — 返回操作結(jié)果描述
as
begin
set nocount on
set xact_abort on
set @RetTotal = 0
set @RetCount = 0
set @RetPageIndex = @PageIndex
— 多條件取值
declare @Err int — 錯誤
declare @PageCount int — 總頁數(shù)
declare @BeginRID int — 開始行 Rid
declare @MaxRow int — 最后行
select @RetTotal = count(*)
from NationTask
select @Err = @@ERROR
if @Err 0
begin
set @ReturnDesc = ‘提取國家任務(wù)總數(shù)失敗!’
return -1
end
— 如果無數(shù)據(jù), 則返回空結(jié)果集
if @RetTotal = 0
begin
set @ReturnDesc = ‘當(dāng)前條件無國家任務(wù)記錄!’
return 1
end
— 計算總頁數(shù)
set @PageCount = @RetTotal / @PageSize
if @RetTotal % @PageSize > 0
begin
set @PageCount = @PageCount + 1
end
— 超過總頁數(shù),則返回空結(jié)果集
if @PageIndex > @PageCount
begin
set @ReturnDesc = ‘當(dāng)前條件無國家任務(wù)記錄!’
return 1
end
— 獲取 要返回頁面的 第一行紀錄的 Rid
set @MaxRow = @PageSize * (@PageIndex – 1) + 1
set rowcount @MaxRow
select @BeginRID = Rid
from NationTask
order by Rid desc
— 返回數(shù)據(jù)列表
set rowcount @PageSize
select Rid
,TaskName
,TaskTitle
,ImageID
,EffectID
,StartTime
from NationTask
where Rid order by Rid desc
set @RetCount = @@rowcount
— 結(jié)束
set @ReturnDesc = ‘提取國家任務(wù)列表成功!’
return 1
end