SQL SERVER/ROW_NUMBER() OVER (ORDER BY id)高效分页

SELECT TOP 页大小 * 
FROM 
    (
        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)

简单的说row_number()从1开始,为每一条分组记录返回一个数字

猜你喜欢

转载自www.cnblogs.com/Jayesslee/p/9342341.html