您现在的位置是:网站首页> 编程资料编程资料
SQL Server实现分页方法介绍_MsSql_
2023-05-26
356人已围观
简介 SQL Server实现分页方法介绍_MsSql_
一、创建测试表
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实现分页方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
您可能感兴趣的文章:
相关内容
- SQL Server中常用截取字符串函数介绍_MsSql_
- 通过T-SQL语句创建游标与实现数据库加解密功能_MsSql_
- sql语句中union的用法与踩坑记录_MsSql_
- SQL利用游标遍历日期查询的过程详解_MsSql_
- MSSQL 附加数据库提示“错误 823”数据恢复实操_MsSql_
- sqlserver数据库加密后无法使用MDF,LDF,log文件名称被修改的数据恢复_MsSql_
- SQL Server查询某个字段在哪些表中存在_MsSql_
- 详解SQL之CASE WHEN具体用法_MsSql_
- sql时间段切分实现每隔x分钟出一份高速门架车流量_MsSql_
- 使用SQL实现车流量的计算的示例代码_MsSql_
