SQLServer简单分页存储过程的写法

写法一:
create proc p_page
(
@name varchar(50),--模糊查询
@index int, --当前页
@size int,  --大小
@total int out, --总记录数
@count int out --总页数
)
as
begin
 --首先对当前页判断 既不能小于1也不能大于总页数
 if @index<1
  set @index=1;
 --先计算总记录数
 select @total=Count(*) from GoodsInfoes where GName like '%'+@name+'%';
 --计算总页数
 set @count=CEILING(@total*1.0/@size);
 --判断当前页是否大于总页数
 if @index>@count
  set @index=@count
 --分页查询
 select * from
 (select g.Id,g.GName,g.GPrice,g.GNum,g.TypeInfoId,t.TName,ROW_NUMBER() over(order by g.Id) rn from GoodsInfoes g left join TypeInfoes t on g.TypeInfoId=t.Id where g.GName like '%'+@name+'%') t1
 where rn between (@index-1)*@size+1 and @index*@size;
end
go
declare @total int,@count int
exec p_page '',1,2,@total out,@count out
select @total,@count
 
写法二:利用not in
 
create proc p_page1
(
@name varchar(50),
@index int, --当前页
@size int,  --大小
@total int out, --总记录数
@count int out --总页数
)
as
begin
 --首先对当前页判断 既不能小于1也不能大于总页数
 if @index<1
  set @index=1;
 --先计算总记录数
 select @total=Count(*) from GoodsInfoes where GName like '%'+@name+'%';
 --计算总页数
 set @count=CEILING(@total*1.0/@size);
 --判断当前页是否大于总页数
 if @index>@count
  set @index=@count
 --分页查询
 select top(@size) * from GoodsInfoes g join TypeInfoes t on g.TypeInfoId=t.Id
 where g.GName like '%'+@name+'%' and g.Id not in
 (select top((@index-1)*@size) g.Id from GoodsInfoes g join TypeInfoes t on g.TypeInfoId=t.Id
  where g.GName like '%'+@name+'%' order by g.id
 ) order by g.Id;
end
go
declare @total int,@count int
exec p_page1 '冰箱',1,2,@total out,@count out
select @total,@count
 
 
 
原文地址:https://www.cnblogs.com/sxkang/p/13442184.html