select * from Books
go
--判断存储过程是否存在
if exists(select 1 from sysobjects where [name]='books_pager')
drop procedure books_pager --如果此存储过程存在,就删除
go
--创建分页存储过程books_pager
create proc books_pager
@pageSize int, --每页显示多少条记录【输入】
@pageIndex int, --当前页数【输入】
@totalPages int output --总页数【输出】
as
declare @startIndex int --定义开始位置
declare @endIndex int --定义结束位置
declare @totalRows int --定义总行数
select @totalRows = COUNT(*) from Books --查询表一共多少条记录
set @totalPages=@totalRows/@pageSize --总页数=总行数/每页要显示的条数
if(@totalRows/@pageSize!=0) --如果不能整除的情况下
begin
set @totalPages=@totalPages+1 --总页数+1
end
set @startIndex=(@pageIndex-1)*@pageSize+1
set @endIndex=@startIndex+@pageSize-1
declare @bookTemp table([id] int identity(1,1)not null,bookId int) --创建临时表@bookTemp
insert @bookTemp select ID from Books --查询出Books表里面的ID插入到临时表中
select * from @bookTemp as t,Books as b
where t.bookId=b.Id and t.id>=@startIndex and t.id<=@endIndex --根据开始和结束位置查询要显示的哪一页
go
--测试存储过程
declare @totalPages int
exec books_pager 3,1,@totalPages output
print @totalPages --输出总页数
分页存储过程
最新推荐文章于 2021-09-25 23:33:08 发布