利用Sql Server的top分页查询的通用构造方式

Sql Server中,假设一个查询sql为querySql,该sql为任意条件的组合,我们把它当作子查询结果表,可利用Sql Server的top来构造通用的分页查询sql:

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

你可能感兴趣的:(sql,SQL Server,idea)