当前位置:Gxlcms > 数据库问题 > sqlserver 分页

sqlserver 分页

时间:2021-07-01 10:21:17 帮助过:23人阅读

参考资料:SQL分页语句

第一种方法:效率最高

 

?
1 2 3 4 5 6 7 8 9 10 11 SELECT TOP 页大小 * FROM     (         SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1     )   as temp   WHERE RowNumber > 页大小*(页数-1) ORDER BY id   --注解:首先利用Row_number()为table1表的每一行添加一个行号,给行号这一列取名‘RowNumber‘ 在over()方法中将‘RowNumber‘做了升序排列 --然后将‘RowNumber‘列 与table1表的所有列 形成一个表A --重点在where条件。假如当前页(currentPage)是第2页,每页显示10个数据(pageSzie)。那么第一页的数据就是第11-20条 --所以为了显示第二页的数据,即显示第11-20条数据,那么就让RowNumber大于 10*(2-1) 即:页大小*(当前页-1)

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

 

?
1 2 3 4 5 6 7 8 9 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) ORDER BY locid
技术分享图片

第二种方法:效率次之

 

?
1 2 3 4 5 6 7 8 9 10 11 SELECT TOP 页大小 *  --如果每页显示10条数据,那么这里就是查询10条数据 FROM table1 WHERE id >  --假如当前页为第三页,那么就需要查询21-30条数据,即:id>20         (             SELECT ISNULL(MAX(id),0)  --查询子查询中最大的id             FROM                 (                     SELECT TOP 页大小*(当前页-1) id FROM table1 ORDER BY id --因为当前页是第三页,每页显示十条数据。那么我将: 页大小*(当前页-1),就是获取到了在"当前页""前面"的20条数据。所以上面用max(id)查询最大的id,取到这个20,那么前面的where 条件的id>20 即取到了第三页的数据,即取21-30条数据                 ) as A            ) ORDER BY id

将上面的方法写成存储过程:表名Location ?
1 2 3 4 5 6 7 8 9 10 if(exists(select * from sys.procedures where name=‘p_location_paging‘)) drop proc p_location_paging go create proc p_location_paging(@pageSize int ,@currentPage int) as select  top (@pageSize) * from location where locId>(select ISNULL(MAX(locId),0) from (select top ((@pageSize)*(@currentPage-1))locid from location  order by locId) as a ) order by locId

第三种方法:效果最差

 

?
1 2 3 4 5 6 7 8 SELECT TOP 页大小 * FROM table1 WHERE id NOT IN --where条件语句限定要查询的数据不是子查询里面包含的数据。即查询"子查询"后面的10条数据。即当前页的数据         (            --如果当前页是第二页,每页显示10条数据,那么这里就是获取当前页前面的所有数据。            SELECT TOP 页大小*(当前页-1) id FROM table1 ORDER BY id         ) ORDER BY id

 

 

sqlserver 分页

标签:add   10个   article   string   html   syntax   roc   效率   class   

人气教程排行