分页

分页需要知道哪些数据?
a 页大小:每页显示多少条数据PageSize
b 当前页:当前显示第几页数据CurrentPageIndex
c 总页数: 按照页大小分配,表中的所有数据总共分几页显示。
 
1 使用not in、子查询     ROW_NUMBER()
a 使用not in、子查询
select top PageSize * from 表

 where 条件 and id not in
 (
  select top PageSize * (CurrentPageIndex -1)  id
   from 表 where 条件 order by 排列顺序
 )
order by 排列顺序
b --使用ROW_NUMBER()
即:加了一个id列。即使删除数据也不会影响排序。
缺点:SQL2005以前没有这个函数。不通用。
select * from

 (select ROW_NUMBER() over(order by categoryID) as 编号, * from GoodsItem) as GoodsItems
  where categoryID between 3 and 4
   order by categoryID
 
Note : 子查询结果是表则需要为表命名(使用as)。
 
2 存储过程
create proc pro_Page

@PageSize int,
@CurrentPageIndex int,
@PageCount int output
as
declare @totalCount int
select @totalCount = Count(*) from 表
---计算总页数
if(@totalCount % 2 =0)
 set @PageCount = @totalCount/@PageSize
else
 set @PageCount = @totalCount/@PageSize +1
---分页显示的SQL语句
select top PageSize * from 表
 where 条件 and id not in
 (
  select top PageSize * (CurrentPageIndex -1)  id
   from 表 where 条件 order by 排列顺序
 )
order by 排列顺序
Note: 如果存储过程带输出参数或者返回值,不能用DataReader保存查询结果,DataReader读不到,用DataSet
原文地址:https://www.cnblogs.com/Jokers/p/3140121.html