Sql分页语句

今天闲来无事,测试了一下用Sql分页语句,从网上找了一些数据,总结Sql分页分为5种:

--写法1,not in/top
select top 50 * from pagetest 
where id not in (select top 9900 id from pagetest order by id)
order by id

--写法2,not exists
select top 50 * from pagetest 
where not exists 
(select 1 from (select top 9900 id from pagetest order by id)a  where a.id=pagetest.id)
order by id

--写法3,max/top
select top 50 * from pagetest
where id>(select max(id) from (select top 9900 id from pagetest order by id)a)
order by id

--写法4,row_number()
select top 50 * from 
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>9900

select * from 
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber>9900 and rownumber<9951

select * from 
(select row_number()over(order by id)rownumber,* from pagetest)a
where rownumber between 9901 and 9950

--写法5,在csdn上一帖子看到的,row_number() 变体,不基于已有字段产生记录序号,先按条件筛选以及排好序,再在结果集上给一常量列用于产生记录序号
select *
from (
    select row_number()over(order by tempColumn)rownumber,*
    from (select top 9950 tempColumn=0,* from pagetest where 1=1 order by id)a
)b
where rownumber>9900

 做一个简单的大数据测试,用一百万的数据,来检测一下上面五种sql语句的执行效率时间:

create database DBTest
use DBTest

--创建测试表
create table pagetest
(
id int identity(1,1) not null,
col01 int null,
col02 nvarchar(50) null,
col03 datetime null
)

--1万记录集
declare @i int
set @i=0
while(@i<1000000)
begin
    insert into pagetest select cast(floor(rand()*10000) as int),left(newid(),10),getdate()
    set @i=@i+1
end
---测试sql执行的时间语句
declare @begin_date datetime
declare @end_date datetime
select @begin_date = getdate()

<.....YOUR CODE.....>

select @end_date = getdate()
select datediff(ms,@begin_date,@end_date) as '毫秒'

 经过测试,用row_number()方法效率最为高效,用时最少;

posted @ 2013-12-31 11:51  贝小贝  阅读(180)  评论(0编辑  收藏  举报