很久没更新了,最近忙的很,也生病了,重感冒,555~~~数据库
早上抽的一丝空闲,来说讲SqlServer中的分页问题。其实用过了多种数据库,分页这问题已是老生常谈的问题了。无论是开发什么类型的网站,只要是包含检索功能的,不外乎会涉及到分页的问题。函数
好比Oracle中的分页:网站
select * from (select a.*,rownum rc from 表名 where rownum<=endrow) a where a.rc>=startrowspa
select a1.* from (select student.*,rownum rn from student) a1 where rn between startpage and endpage;(使用较多)开发
DB2中的分页:table
Select * from (select rownumber() over() as rc,a.* from (select * from 表名 order by 列名) as a) where rc between startrow and endrowclass
MySQL中的分页:(感受是全部数据库中最简单并且写法统一的了)select
而针对SqlServer中的分页有多种:分页
经常使用的是用到了row_number()函数,可是只支持SqlServer2005及以上版本语法
select top pagenum * from (select row_number()over(order by id)rownumber,* from a)a1 where rownumber>startpage
select * from (select row_number()over(order by id)rownumber,* from a) a1 where rownumber>startpage and rownumber<endpage+1
select * from (select row_number()over(order by id)rownumber,* from a) a1 where rownumber between startpage+1 and endpage
还有这种:
select top pagenum * from a where not exists (select 1 from (select top 30 id from a order by id)a1 where a1.id=a.id) order by id
可是我想说的是被好多人所不关注的一种分页方法:
select * from 表 order by id OFFSET PageIndex*pagenum ROWS FETCH next pagenum rows only
这种方法是否是很简单,可是这个只有在SQL Server 2012及以上版本中才能使用,不管是从逻辑读取数仍是响应时间、实际执行行数等关键参数看,SQL Server 2012提供的OFFSET/FETCH NEXT分页方式都比Row_Number()方式有了较大的提高。
注意:使用该方法必须使用order by ,否则会有语法错误。