当前位置:Gxlcms > 数据库问题 > SQL2012分页offset fetch 比较SQL2005/2008的ROW_Number

SQL2012分页offset fetch 比较SQL2005/2008的ROW_Number

时间:2021-07-01 10:21:17 帮助过:2人阅读

 BY order_by_expression
    [ COLLATE collation_name ] 
    [ ASC | DESC ] 
    [ ,...n ] 
[ <offset_fetch> ]


<offset_fetch> ::=

    OFFSET { integer_constant | offset_row_count_expression } { ROW | ROWS }
    [
      FETCH { FIRST | NEXT } {integer_constant | fetch_row_count_expression } { ROW | ROWS } ONLY
    
]
}

 

2.OFFSET和FETCH的简单用法

--创建表
CREATE TABLE [dbo].[TestColumnStore_tcs](
 [tcs_id] [int] IDENTITY(1,1NOT NULL,
 [tcs_data] [int] NULL
ON [PRIMARY]
--插入100万条测试数据,

--select * from TestColumnStore_tcs
--
select FLOOR(RAND(ABS(CHECKSUM(NEWID())))*100)  --获取随机值

declare @index int
set @index=0
while(@index<1000000)
begin
 insert into TestColumnStore_tcs(tcs_data) values(FLOOR(RAND(ABS(CHECKSUM(NEWID())))*100))
 set @index=@index+1
end

 

使用OFFSET和FETCH关键字使分页变得如此简单。

--取50万到500020之间的数据
select * from TestColumnStore_tcs order by tcs_id offset 500000 row fetch next 20 rows only

技术分享
 

3..OFFSET…FETCH分页对性能的提升
    OFFSET和FETCH语句不仅仅是语法糖,还能带来分页效率上的提升。下面我们通过一个例子进行比较SQL Server 2012和SQL Server 2005/2008不同分页方式的分页效率。我们同样取50万到500100之间的数据,性能对比所示。

 

 

--SQL2012分页方式
select * from TestColumnStore_tcs order by tcs_id offset 500000 row fetch next 20 rows only;
--SQL2008、2005分页方式
with cte as (
select ROW_NUMBER() over(order by tcs_id) as aa,* from TestColumnStore_tcs)
select * from cte where aa>500000 and aa<=500020

下图:SQL Server 2012分页和SQL Server 05/08之间分页效率对比

技术分享

 

下图: 查询计划中我看到SQL Server2012中FETCH..NEXT十分损耗性能。

技术分享

 

 

 

SQL Server 2012带来的分页效果十分强大,使得大大简化在SQL Server下的分页。对于性能的影响,由于出现了上述执行计划的偏差,暂且不下结论

 

SQL2012分页offset fetch 比较SQL2005/2008的ROW_Number

标签:

人气教程排行