共计 2006 个字符,预计需要花费 6 分钟才能阅读完成。
这期内容当中丸趣 TV 小编将会给大家带来有关 SQL Server 中如何使用 row_number 实现分页,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
1、首先是
select ROW_NUMBER() over(order by id asc) as rowNumber , * from table1
生成带序号的集合
2、再查询该集合的 第 1 到第 5 条数据
select * from (select ROW_NUMBER() over(order by id asc) as rowNumber , * from table1) as temp where rowNumber between 1 and 5
完整的 Sql 语句
declare @pagesize int; declare @pageindex int; set @pagesize = 3set @pageindex = 1; -- 第一页 select * from (select ROW_NUMBER() over(order by id asc) as rowNumber , * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)set @pageindex = 2; -- 第二页 select * from (select ROW_NUMBER() over(order by id asc) as rowNumber , * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)set @pageindex = 3; -- 第三页 select * from (select ROW_NUMBER() over(order by id asc) as rowNumber , * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)set @pageindex = 4;-- 第四页 select * from (select ROW_NUMBER() over(order by id asc) as rowNumber , * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)
下面我们来写个存储过程分页
Alter Procedure PagePager @TableName varchar(80), @File varchar(1000),--- @Where varchar(500),--- 带 and 连接 @OrderFile varchar(100), -- 排序字段 @OrderType varchar(10),--asc: 顺序,desc: 倒序 @PageSize varchar(10), -- @PageIndex varchar(10) -- as if(ISNULL(@OrderFile, ) = ) begin set @OrderFile = ID end if(ISNULL(@OrderType,) = ) begin set @OrderType = asc end if(ISNULL(@File,) = ) begin set @File = * end declare @select varchar(8000) set @select = select + @File + from ( select *,ROW_NUMBER() over(order by + @OrderFile + + @OrderType + ) as rowNumber from + @TableName + where 1=1 + @Where + ) temp where rowNumber between ((( + @PageIndex + - 1) * + @PageSize + )+1) and ( + @PageIndex + * + @PageSize+) exec(@select)
上述就是丸趣 TV 小编为大家分享的 SQL Server 中如何使用 row_number 实现分页了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注丸趣 TV 行业资讯频道。
正文完