create database DBTest
use DBTest
if exists(select * from sysobjects where name='pagetest')
drop table pagetest
go
--创建测试表
create table pagetest
(
id int identity(1,1) not null,
col01 int null,
col02 nvarchar(50) null,
col03 datetime null
)
--1万记录集
declare @i int
set @i=0
while(@i<10000)
begin
insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate()
set @i=@i+1
end
--开始创建存储过程
if exists(select * from sysobjects where name='proc_2')
drop proc proc_2
go
create proc proc_2
--输入参数
@pagesize int,--每页记录条数5
@pageindex int,--当前要查看第几页的记录1
@Name nvarchar(50), --查询字段
--@id int, --查询字段
--输出参数
@recordcount int output,--总的记录的条数
@pagecount int output --总的页数
as
begin
select * into #pagetest_1 from (select *,rn = row_number() over(order by pagetest.id asc) from pagetest where 1=1 and col02 like '%' + @Name + '%') as s --创建临时表
select * from (select * from (select *,rn = row_number() over(order by pagetest.id asc) from pagetest where 1=1 and col02 like '%' + @Name + '%') as s
where rn between (@pageindex - 1)*@pagesize+1 and @pageindex*@pagesize)
as t where 1=1 --具体语句
set @recordcount = (select COUNT(*) from #pagetest_1)
set @pagecount= ceiling(@recordcount*1.0/@pagesize) --乘以1.0转成flot型, 然后celling “进一法”取值
end
declare @re int, @pa int
exec proc_2 @pagesize = 10,@pageindex = 1,@Name = 'B',@recordcount = @re output,@pagecount = @pa output
print @re
print @pa
第一次发布博客,学的比较浅,所以写的东西不深,其中也有一部分是借鉴网上的代码,比如添加1w调数据,然后就是说发表一下自己的意见,这个是带查询变量的分页,这只是个基本的雏形,至于想要带几个字段查询看各自的业务需求,我就说一下我感觉比较关键的几个地方就是
rn = row_number() over(order by pagetest.id asc)
新生成rn列记录排序,然后根据
(@pageindex - 1)*@pagesize+1 开始,到@pageindex*@pagesize结束,就是显示的(页码-1)*显示的行数+1 //为了让让起始数据从第一条数据开始,到后面的页码*现实的行数就很好理解了。至于那张临时表的话,我是为了下面的输出当前的页数和当前的所有数据行数准备的。剩下的大家看看注释就应该能懂。毕竟都是大佬哈。
如果有不对的地方,请各位大佬即时点出,我会即时改正,以免误人子弟。