sqlserver2008不支持关键字limit ,所以它的分页sql查询语句将不能用mysql的方式进行,幸好sqlserver2008提供了top,rownumber等关键字,这样就能通过这几个关键字实现分页。
--top not in方式
select top 条数 * from tablename
where Id not in (select top 条数*页数 Id from tablename)
--ROW_NUMBER() OVER()方式
select * from (
select *, ROW_NUMBER() OVER(Order by Id ) AS RowNumber from tablename
) as b
where RowNumber BETWEEN 当前页数-1*条数 and 页数*条数
--offset fetch next方式
--SQL2012以上的版本才支持
select * from tablename
order by Id offset 行数 row fetch next 条数 row only
关键字解析:
- Offset子句:用于指定跳过(Skip)的数据行;
- Fetch子句:该子句在Offset子句之后执行,表示在跳过(Sikp)指定数量的数据行之后,返回一定数据量的数据行;
- 执行顺序:Offset子句必须在Order By 子句之后执行,Fetch子句必须在Offset子句之后执行;
分页实现的思路:
- 在分页实现中,使用Order By子句,按照指定的columns对结果集进行排序;
- 使用Offset子句跳过前N页:Offset (@PageIndex-1)*@RowsPerPage rows;
- 使用Fetch子句呈现当前Page:Fetch next @RowsPerPage rows only;