当前位置: 首页 > 图文教程 > 数据库 > MSSQL > 分页查询 效率最高

MSSQL
在SQL Server 2005数据库中更改数据架构
建立适当的索引是实现查询优化的首要前提
巧用一条SQL 实现其它进制到十进制转换
处理SQL Server 2000的命名实例和多实例
解析:怎样掌握SQL Server中的数据查询
教你轻松掌握常用的子句、关键词和函数
如何获取SQL Server数据库元数据的方法
分析SQL Server中数据库的快照工作原理
汇总数据库备份 还原 压缩与数据库转移的方法
完全讲解 使用MSCS建立SQL Server集群
SQL Server 2005 内置工具建审查系统
在SQL Server计算机上运行病毒扫描软件
教你如何升级SQL Server数据库系统
SQL Server中处理空值时涉及的三问题
教你为SQL Server数据库构造安全门
在SQL Server中编写通用数据访问方法
针对SQL Server中业务规则链接的分析
运行SQL Server的计算机间移动数据库
怎样在不同版本SQL Server中存储数据
认识那些被忽略的SQL Server注入技巧

MSSQL 中的 分页查询 效率最高


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 125 ::
收藏到网摘: n/a

给大家分享个效率最高的分页查询 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 <= @BeginRID
order by Rid desc
set @RetCount = @@rowcount
-- 结束
set @ReturnDesc = '提取国家任务列表成功!'
return 1
end