分页存储过程

来源:互联网 发布:算法设计沙特答案 编辑:程序博客网 时间:2024/05/16 01:52
select * from Booksgo--判断存储过程是否存在if exists(select 1 from sysobjects where [name]='books_pager')drop procedure books_pager --如果此存储过程存在,就删除go--创建分页存储过程books_pagercreate proc books_pager@pageSize int, --每页显示多少条记录【输入】@pageIndex int, --当前页数【输入】@totalPages int output --总页数【输出】asdeclare @startIndex int --定义开始位置declare @endIndex int --定义结束位置declare @totalRows int --定义总行数select @totalRows = COUNT(*) from Books --查询表一共多少条记录set @totalPages=@totalRows/@pageSize --总页数=总行数/每页要显示的条数if(@totalRows/@pageSize!=0) --如果不能整除的情况下beginset @totalPages=@totalPages+1 --总页数+1endset @startIndex=(@pageIndex-1)*@pageSize+1set @endIndex=@startIndex+@pageSize-1declare @bookTemp table([id] int identity(1,1)not null,bookId int) --创建临时表@bookTempinsert @bookTemp select ID from Books --查询出Books表里面的ID插入到临时表中select * from @bookTemp as t,Books as bwhere t.bookId=b.Id and t.id>=@startIndex and t.id<=@endIndex --根据开始和结束位置查询要显示的哪一页go--测试存储过程declare @totalPages intexec books_pager 3,1,@totalPages outputprint @totalPages --输出总页数