CREATE procedure pTest
(@pagesize int,
@pageindex int,
@docount bit,
@this_id int)
as
if(@docount=1)
begin
select count(id) from luntan where this_id=@this_id
end
else
begin
declare @PageLowerBound int
declare @PageUpperBound int
set @PageLowerBound=(@pageindex-1)*@pagesize
set @PageUpperBound=@PageLowerBound+@pagesize
create table #pageindex(id int identity(1,1) not null,nid int)
set rowcount @PageUpperBound
insert into #pageindex(nid)
select id from luntan where this_id=@this_id order by reply_time desc
select O.*
from luntan O,#pageindex p
where O.id=p.nid and p.id>@PageLowerBound and p.id<=@PageUpperBound order by p.id
end
存储过程会根据传入的参数@docount来确定是不是要返回所有要分页的记录总数
set rowcount @PageUpperBound当记录数达到@PageUpperBound时就会停止处理查询
select id 只把id列取出放到临时表里,select a.* from luntan a,@indextable t where a.id=t.nid
and t.id>@PageLowerBound and t.id<=@PageUpperBound order by t.id
而这句也只从表中取出所需要的记录,而不是所有的记录