SQL Server实现分页方法介绍
作者:.NET开发菜鸟 时间:2024-01-15 12:54:45
一、创建测试表
CREATE TABLE [dbo].[Student](
[id] [int] NOT NULL,
[name] [nvarchar](50) NULL,
[age] [int] NULL)
二、创建测试数据
declare @i int
set @i=1
while(@i<10000)
begin
insert into Student select @i,left(newid(),7),@i+12
set @i += 1
end
三、测试
1、使用top关键字
top关键字表示跳过多少条取多少条
declare @pageCount int --每页条数
declare @pageNo int --页码
declare @startIndex int --跳过的条数
set @pageCount=10
set @pageNo=3
set @startIndex=(@pageCount*(@pageNo-1))
select top(@pageCount) * from Student
where ID not in
(
select top (@startIndex) ID from Student order by id
) order by ID
测试结果:
2、使用row_number()函数
declare @pageCount int --页数
declare @pageNo int --页码
set @pageCount=10
set @pageNo=3
--写法1:使用between and
select t.row,* from
(
select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row between (@pageNo-1)*@pageCount+1 and @pageCount*@pageNo
--写法2:使用 “>”运算符
select top (@pageCount) * from
(
select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row >(@pageNo-1)*@pageCount
--写法3:使用and运算符
select top (@pageCount) * from
(
select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row >(@pageNo-1)*@pageCount and t.row<(@pageNo)*@pageCount+1
四、总结
ROW_NUMBER()只支持sql2005及以上版本,top有更好的可移植性,能同时适用于sql2000及以上版本、access。
这篇文章介绍了SQL Server实现分页方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
来源:https://www.cnblogs.com/dotnet261010/p/10784315.html
标签:SQL,Server,分页
0
投稿
猜你喜欢
Python判断一个三位数是否为水仙花数的示例
2021-11-06 06:14:13
Python快速实现一键抠图功能的全过程
2021-03-03 14:58:39
python能自学吗
2023-09-25 09:33:47
Go语言映射内部实现及基础功能实战
2024-04-27 15:39:30
CSS教程:关于网页图片的属性的介绍
2008-10-31 12:02:00
JSONObject使用方法详解
2024-05-03 15:06:47
python安装cxOracle避坑总结不要直接pip install
2023-12-07 09:13:11
python matplotlib库直方图绘制详解
2023-01-19 06:38:34
Python %r和%s区别代码实例解析
2023-10-07 17:01:08
pytorch中的weight-initilzation用法
2022-03-22 23:28:24
SQL2005CLR函数扩展-数据导出的实现详解
2024-01-25 11:59:57
Python中的defaultdict模块和namedtuple模块的简单入门指南
2022-01-21 07:10:20
基于PHP选项与信息函数的使用详解
2024-05-13 09:23:34
Python实现公历(阳历)转农历(阴历)的方法示例
2021-08-02 09:54:44
python美多商城项目开发小结
2022-09-05 08:01:48
asp清理站点缓存代码
2008-07-21 12:37:00
Python及PyCharm下载与安装教程
2022-10-04 08:19:54
python单例模式获取IP代理的方法详解
2023-11-14 22:22:05
mysql慢查询优化之从理论和实践说明limit的优点
2024-01-26 11:59:51
pydantic-resolve嵌套数据结构生成LoaderDepend管理contextvars
2023-01-12 22:21:05