您的位置:首页 > 博客中心 > 数据库 >

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

时间:2022-03-14 03:25


第一种方法效率最高

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)


热门排行

今日推荐

热门手游