使用Sql Server分页查询是SQL数据库最常见的操作之一,下面将为您介绍两种利用top构造Sql Server分页查询的方法,供您参考。
Sql Server中,假设一个查询sql为querySql,该sql为任意条件的组合,我们把它当作子查询结果表,可利用Sql Server的top来构造通用Sql Server分页查询:
- if (pageInfo.getPageNum() == 1) {
- pagenatedSql = "select top " + pageInfo.pageSize + " * from (" + sql + ") as t1 " ;
- }
- else {
- pagenatedSql = "select top " + pageInfo.pageSize + " * from (" + sql + ") as t1 " +
- " where (t1." + indexKey + " > (select max(t3." + indexKey + ")" +
- " from (select top " + (pageInfo.pageNum - 1) * pageInfo.pageSize + " t2." + indexKey + " from (" + sql + ") as t2 order by t2." + indexKey + ") as t3" +
- " )) order by t1." + indexKey;
- }
其中pageInfo.getPageNum()为当前页号(从1开始);pageInfo.getPageSize()为每页行数;indexKey为表中索引列,通常为递增的主键。
第二种方式:
pagesize: 每页显示记录数
cureentpage:当前页数
- select * from ( select TOP pagesize * FROM ( SELECT TOP pagesize*cureentpage * from user_table ORDER BY id ASC ) as aSysTable ORDER BY id DESC ) as bSysTable ORDER BY id ASC
以上就是利用top构造Sql Server分页查询的方法。
【编辑推荐】