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