SQLServer数据分页

一.分页

将一定量的数据进行分页,每一页中定量存储数据

1.top分页查询

比如当前存在于数据库中的一共有40条数据,我们将每10条数据算作一页,那么一共可以分出4页,如果要进行查询的话,只需要使用如下格式即可:

sql 复制代码
--查询第一页
select top 5 * from Student 
--查询第二页
select top 5 * from Student 
where Id not in(1,2,3,4,5,6,7,8,9,10)

注意点:虽然我们一般所使用的Id自增长形式为identity(1,1),即从1开始,每次增长1,但是在我们查询分页时还是要注意Id的自增长形式,避免出错

而从上方的示例中不知道你们有没有发现一个规律,写出来是这样的:

select top 页码 * from 表名

where Id not in(select top 页码*(当前页-1) Id from 表名)

所以正确的分页查询格式应该为:

sql 复制代码
select top 5 * from Student 
where Id not in(select top 0 Id from Student) 
select top 5 * from Student 
where Id not in(select top 5 Id from Student)
select top 5 * from Student 
where Id not in(select top 10 Id from Student)

若是运用了变量,那么就更容易理解了

sql 复制代码
declare @Size int = 5 
declare @Page int = 1 
select top (@Size) * from Student 
where Id not in(select top (@Size * (@Page - 1)) Id from Student) 

只需要修改Page变量(页数),就可以查询到该页的数据了

2.row_number分页查询

格式为:

sql 复制代码
select * from 
(select row_number() over(order by Id) RowId,* from Student) 
where Id between (当前页号-1) * 每页大小 + 1 and 当前页号 * 每页大小 

同样使用到变量进行举例:

sql 复制代码
declare @Size int = 5 
declare @Page int = 1
select * from 
(select row_number() over(order by Id) RowId,* from Student) 
where Id between (@Page-1) * @Size + 1 and @Page * @Size  
相关推荐
云边有个稻草人2 分钟前
Ubuntu部署Prometheus与Alertmanager:服务接入和远程监控
数据库·ubuntu·prometheus
Hoxy.R4 分钟前
记录一次Oracle 19c RAC iSCSI会话反复重连:comm error (1020) 原因定位与解决
数据库·oracle
神王宝宝 王者小学9 小时前
HBase: 看上去很美
大数据·数据库·hbase
io无心9 小时前
Shardingsphere5分库分表
数据库·mysql
wWYy.10 小时前
Mysql:主键索引 唯一索引 普通索引 前缀索引
数据库·mysql
宝杰X710 小时前
Android Room3 多平台数据库
android·数据库
sky_81061314 小时前
Oracle ERP 各模块业务管理功能及底层表说明
数据库·oracle
YMatrix 官方技术社区15 小时前
CittaBase vs. Neo4j :原生图性能实测与混合检索实践
数据库·功能测试·ymatrix
闲猫16 小时前
LangChain / Integrations / Integrations by component / Tool
java·数据库·langchain
xqqxqxxq16 小时前
SQL 连接查询技术笔记
数据库·笔记·sql