常用的分页

1)NOT IN

复制代码
declare @timediff datetime
declare @pageIndex int
declare @pageSize int
declare @sql varchar(500)
set @pageIndex=1
set @pageSize=10
set @timediff=GetDATE()
set @sql='select top ('+cast(@pageSize as varchar)+') * from testTable where (id not in (
select top '+cast(@pageSize*(@pageIndex-1) as varchar)+' id from testTable order by id)) order by id'
exec(@sql)
select datediff(ms,@timediff,Getdate())
复制代码

@pageIndex=1时,运行:0ms(给力啊

@pageIndex=50000时,运行:346ms(怎么50000页就不给力了)

@pageIndex=100000时,运行:326ms(怎么比50000页时还少了?)

2)MAX()

复制代码
declare @timediff datetime
declare @pageIndex int
declare @pageSize int
declare @sql varchar(500)
set @timediff=GetDATE()
set @pageIndex=1
set @pageSize=10
set @sql='select top ('+cast(@pageSize as varchar)+') * from testTable where (id >= (select MAX(id) from (select top '+cast((@pageSize*(@pageIndex-1)+1) as varchar)+' id from testTable order by id) as a)) order by id'
exec(@sql)
select datediff(ms,@timediff,Getdate())
复制代码

@pageIndex=1时,运行:0ms(也是很给力啊

@pageIndex=50000时,运行:123ms(不错)

@pageIndex=100000时,运行:220ms(页数和查询时间成正比)

3)Row_Number()

复制代码
declare @timediff datetime
declare @pageIndex int
declare @pageSize int
declare @sql varchar(500)
set @timediff=GetDATE()
set @pageIndex=1
set @pageSize=10
set @sql='select * from (select *,row_number() over (order by id asc) as RowIndex from testTable) as IDWithRowNumber where RowIndex between '+cast(((@pageIndex-1)*@pageSize)+1 as varchar)+' and '+cast(@pageIndex*@pageSize as varchar)+''
exec(@sql)
select datediff(ms,@timediff,getdate())
复制代码

@pageIndex=1时,运行:0ms(好吧……数据量小的时候都是这尿性)

@pageIndex=50000时,运行:280ms(略逊色)

@pageIndex=100000时,运行:580ms(这货居然也是页数和查询时间成正比!坑爹吧!)

4)临时表

复制代码
declare @timediff datetime
declare @pageIndex int
declare @pageSize int
declare @sql varchar(500)
declare @str varchar(500)
set @timediff=GetDATE()
set @pageIndex=1
set @pageSize=10
set @str='with tempTable as (select ceiling((Row_number() over (order by id asc))/'+cast(@pageSize as varchar)+') as page_num,* from testTable)'
set @sql=@str+'select * from tempTable where page_num='+cast(@pageIndex-1 as varchar)+''
exec(@sql)
select datediff(ms,@timediff,getdate())
复制代码

@pageIndex=1时,运行:280ms(不咧个是吧!这非主流啊)

@pageIndex=50000时,运行:280ms(这不科学……)

@pageIndex=100000时,运行:280ms(好吧,这货不受页数的影响,永远都这速度)

5)中间变量

复制代码
declare @timediff datetime
declare @pageIndex int
declare @pageSize int
declare @count int
declare @id int
declare @sql varchar(500)
set @pageIndex=1
set @pageSize=10
select @id=0,@count=0,@timediff=GetDATE()
select @count=@count+1,@id=case when @count=(@pageIndex-1)*@pageSize then id else @id end from testTable order by id
set @sql='select top '+cast(@pageSize as varchar)+' * from testTable where id>'+cast(@id as varchar)+''
exec(@sql)
select datediff(ms,@timediff,getdate())
复制代码

 

posted @ 2013-01-24 11:37  上海-天浩  阅读(155)  评论(0编辑  收藏  举报

Living in ShangHai

Copyright © 2008 天浩阁 Corporation, All Rights Reserved