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  
相关推荐
devpotato21 分钟前
缓存与数据库更新顺序不一致问题
java·数据库·redis
天若有情67325 分钟前
Node+MySQL小型全栈笔记项目实战课程分享
数据库·笔记·mysql
wxwx_bscxy3221 小时前
基于springboot宠物领养系统的设计与实现
数据库·spring boot·后端·spring·宠物
九月要晚安1 小时前
达梦DW与AFC对比
数据库
实战派K8S&DB2 小时前
如何在内网配置 TiDB 数据库 Agent
数据库·人工智能·分布式·tidb
实战派K8S&DB2 小时前
《基于 Dify + FastAPI + PyTiDB 搭建大模型驱动的 TiDB 智能运维 Agent》
运维·数据库·分布式·云原生·tidb·fastapi
SelectDB2 小时前
Apache Doris 5.0 年度版本前瞻(一):构建统一的多模湖仓实时分析平台
大数据·数据库·数据分析
小白学大数据2 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
西索斯coding2 小时前
doubao-seed-2.1-turbo 调用一直 401 怎么办?pro 版同样的 Key 却正常——5 分钟排查定位指南
java·服务器·数据库·ai
袋鼠云数栈3 小时前
整库迁移与分库分表同步:批量数据搬迁的配置简化思路
jvm·数据库·oracle