SQLServer分页
一、创建测试表
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。
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决