码迷,mamicode.com
首页 > 数据库 > 详细

SQL 高效分页(百万条数据)

时间:2014-12-05 17:23:42      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   sp   on   数据   2014   log   as   


第一种方法效率最高

SELECT TOP 页大小 * 
FROM 
	(
	<span style="white-space:pre">	</span>SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1
	)   as A  
WHERE RowNumber > 页大小*(页数-1) 

注解:首先利用Row_number()为table1表的每一行添加一个行号,给行号这一列取名'RowNumber' 在over()方法中将'RowNumber'做了升序排列
然后将'RowNumber'列 与table1表的所有列 形成一个表A
重点在where条件。假如当前页(currentPage)是第2页,每页显示10个数据(pageSzie)。那么第一页的数据就是第11-20条
所以为了显示第二页的数据,即显示第11-20条数据,那么就让RowNumber大于 10*(2-1) 即:页大小*(页数-1)


将上面的方法写成存储过程 (表名Location)

if(exists(select* from sys.procedures where name='p_location_paging'))--如果p_location_paging这个存储过程存在
drop proc p_location_paging  --那么就删除这个存储过程
go
create proc p_location_paging(@pageSize int, @currentPage int)--创建存储过程,定义两个变量'每页显示的条数'和'当前页'
as
select  top (@pageSize) * from (
select ROW_NUMBER() over(order by locid) as rowid ,* from location 
)as a
where rowid> (@pageSize)*((@currentPage)-1)


SQL 高效分页(百万条数据)

标签:style   blog   io   sp   on   数据   2014   log   as   

原文地址:http://blog.csdn.net/fanbin168/article/details/41749509

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!