欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL Server使用row_number分页的实现方法

程序员文章站 2022-07-05 22:02:04
本文为大家分享了sql server使用row_number分页的实现方法,供大家参考,具体内容如下 1、首先是 select row_number() over(or...

本文为大家分享了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 = 3

set @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)

以上就是本文的全部内容,希望对大家学习row_number分页有所帮助。