SQL Server 2012服务端使用OFFSET/FETCH NEXT实现分页

今天看到一篇文章:《SQL Server 2012 - Server side paging demo using OFFSET/FETCH NEXT》,原文地址:

http://beyondrelational.com/modules/29/presentations/483/scripts/12983/sql-server-2012-server-side-paging-demo-using-offsetfetch-next.aspx?utm_source=brnewsletter&utm_medium=email&utm_campaign=2012Apr

作者在文中称,要SQL Server 2012使用OFFSET/FETCH NEXT分页,比SQL Server 2005/2008中的RowNumber()有显著改进。先标记一下,有时间再测试。

其主要分页代码如下:

测试数据:

IF OBJECT_ID('DemoPager2012') IS NOT NULL
    DROP Database DemoPager2012
GO
CREATE Database DemoPager2012
GO
USE DemoPager2012
GO

/*
Setup script to create the sample table and fill it with
sample data.
*/
IF OBJECT_ID('Customers','U') IS NOT NULL
    DROP TABLE Customers

CREATE TABLE Customers (
    CustomerID INT,
    CustomerNumber CHAR(4),
    CustomerName VARCHAR(50),
    CustomerCity VARCHAR(20) )
GO

INSERT INTO Customers (
    CustomerID, CustomerNumber, CustomerName, CustomerCity
)
SELECT
    Number,
    REPLACE(STR(Number, 4), ' ', '0'),
    'Customer ' + STR(number,6),
    CHAR(65 + (number % 26)) + '-City'
FROM master..spt_values WHERE type = 'p'
    AND number BETWEEN 0 AND 999

 SQL Server 2005/2008的RowNumber()

/*
Server side paging demo using ROW_NUMBER() - SQL Server
2005/2008 version.
*/
----DECLARE @d Datetime
----SET @d=getdate();
----SET STATISTICS IO ON;
----GO
----SET STATISTICS TIME ON;
----GO
--SET SHOWPLAN_ALL ON;
--GO

DECLARE @page INT, @size INT
SELECT @page = 3, @size = 10

;WITH cte AS (
    SELECT  TOP (@page * @size)
        CustomerID,
        CustomerName,
        CustomerCity,
        ROW_NUMBER() OVER(ORDER BY CustomerName ) AS Seq,
        COUNT(*) OVER(PARTITION BY '') AS Total
    FROM Customers
    WHERE CustomerCity IN ('A-City','B-City')
    ORDER BY CustomerName ASC
)
SELECT
    *
FROM cte
WHERE seq BETWEEN (@page - 1 ) * @size + 1 AND @page * @size
ORDER BY seq;
GO
----select [语句执行花费时间(毫秒)]=datediff(ms,@d,getdate())
--SET SHOWPLAN_ALL OFF;
--GO
----SET STATISTICS IO OFF;
----GO
----SET STATISTICS TIME OFF;
----GO 


SQL Server 2012中引入的OFFSET/FETCH NEXT(http://msdn.microsoft.com/zh-cn/library/ms188385%28v=sql.110%29.aspx

/*
Server side paging demo using the new enhancements added
in SQL Server 2012
*/

----DECLARE @d Datetime
----SET @d=getdate();
SET STATISTICS IO ON;
GO
SET STATISTICS TIME ON;
GO
--SET SHOWPLAN_ALL ON;
--GO

DECLARE @page INT, @size INT
SELECT @page = 3, @size = 10

SELECT
    *,
    COUNT(*) OVER(PARTITION BY '') AS Total
FROM Customers
WHERE CustomerCity IN ('A-City','B-City')
ORDER BY CustomerID
OFFSET (@page -1) * @size ROWS
FETCH NEXT @size ROWS ONLY;
GO

----select [语句执行花费时间(毫秒)]=datediff(ms,@d,getdate())
--SET SHOWPLAN_ALL OFF;
--GO
SET STATISTICS IO OFF;
GO
SET STATISTICS TIME OFF;
GO
/*
Execute both versions with execution plan turned on.
You may notice a significant performance difference in this
example.
*/
posted @ 2012-04-12 10:40  邀月  阅读(2476)  评论(3编辑  收藏  举报