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  
相关推荐
zhangjw344 分钟前
1-5 PostgreSQL 数据类型全集:基础类型、字符串、数值、时间类型
数据库·postgresql
王中阳Go18 分钟前
5.27 分钟干完后端和全部测试:一场三小时笔试的五个失分点,四个不在代码上
大数据·数据库·人工智能·后端·大语言模型
cnskylee43 分钟前
【MySQL】麒麟V10 SP3系统安装MySQL-Commercial-8.0.46
数据库·mysql·adb
梦幻通灵44 分钟前
修改MySQL数据库递增序列【持续更新】
数据库·mysql
liminla!1 小时前
SQL 从入门到进阶:语法速查与实战练习(完整优化版)
数据库·sql·算法
tongyiixiaohuang1 小时前
供应商主数据同步实战:从易快报到金蝶云星空的单一策略落地
java·网络·数据库
大侠归来2 小时前
常用 MySQL 分库分表方案详解
数据库·mysql
kingx32 小时前
Windows Server 2008 应急加固实战:7 项入侵痕迹排查与修复
数据库·windows·提权·应急响应·加固
xiaogai_gai3 小时前
采购业务退款单同步实战:从钉钉审批流到金蝶云星空付款单
java·数据库·钉钉
AlickLbc4 小时前
DM-V8数据库证书过期处理过程记录
数据库