意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

SQL Server实现分页的过程步骤是什么

来源:恒创科技 编辑:恒创科技编辑部
2023-12-19 12:43:59
很多朋友都对“SQL Server实现分页的过程步骤是什么”的内容比较感兴趣,对此小编整理了相关的知识分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获,那么感兴趣的朋友就继续往下看吧!

一、创建测试表

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关键字表示跳过多少条取多少条


SQL Server实现分页的过程步骤是什么

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实现分页的过程步骤是什么”的相关知识,感谢各位的阅读,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注恒创科技,小编每天都会为大家更新不同的知识。
上一篇: Transact-SQL编程的要点有哪些 下一篇: SQL查询in和notin用法是怎样,有什么要注意的