SQL Server分頁方法匯總

根據SalesOrderID排序,取第16-18行這3條記錄。

方法一:(最常用的分頁代碼, top / not in)

SELECT   TOP 3 [SalesOrderID], [RevisionNumber], [OrderDate]
FROM     [AdventureWorks2012].[Sales].[SalesOrderHeader]
WHERE    [SalesOrderID] NOT IN (   SELECT   TOP 15 [SalesOrderID]
                                    FROM     [AdventureWorks2012].[Sales].[SalesOrderHeader]
                                    ORDER BY [SalesOrderID] )
 ORDER BY SalesOrderID;

備註: 註意前後的order by 一致

方法二:排名開窗函數 (row_number() over (order by ))

SELECT  [SalesOrderID], [RevisionNumber], [OrderDate]
FROM    (   SELECT [SalesOrderID], [RevisionNumber], [OrderDate] ,
                   ROW_NUMBER() OVER ( ORDER BY SalesOrderID ) AS rowid
            FROM   [AdventureWorks2012].[Sales].[SalesOrderHeader] ) cte
WHERE   rowid
BETWEEN 16 AND 18;

方法三:(offset /fetch next, SQL Server 2012支持,性能最好!)

SELECT   [SalesOrderID], [RevisionNumber], [OrderDate]
 FROM     [AdventureWorks2012].[Sales].[SalesOrderHeader]
 ORDER BY SalesOrderID OFFSET 15 ROW FETCH NEXT 3 ROWS ONLY;

總結:利用變量進行分頁

DECLARE @page INT, @size INT, @Total INT;
SELECT @page = 3, @size = 10; --當前頁面為3,頁面大小為10

-------方法一
SELECT   TOP ( @size ) [SalesOrderID], [RevisionNumber], [OrderDate]
FROM     [AdventureWorks2012].[Sales].[SalesOrderHeader]
WHERE    [SalesOrderID] NOT IN (   SELECT   TOP (( @page - 1 ) * @size ) [SalesOrderID]
                                   FROM     [AdventureWorks2012].[Sales].[SalesOrderHeader]
                                   ORDER BY [SalesOrderID] )
ORDER BY SalesOrderID;

-------方法二
SELECT  [SalesOrderID], [RevisionNumber], [OrderDate]
FROM    (   SELECT [SalesOrderID], [RevisionNumber], [OrderDate] ,
                   ROW_NUMBER() OVER ( ORDER BY SalesOrderID ) AS rowid
            FROM   [AdventureWorks2012].[Sales].[SalesOrderHeader] ) cte
WHERE   rowid
BETWEEN ( @page - 1 ) * @size + 1 AND @page * @size;

-------方法三
SELECT   [SalesOrderID], [RevisionNumber], [OrderDate]
FROM     [AdventureWorks2012].[Sales].[SalesOrderHeader]
ORDER BY SalesOrderID OFFSET ( @page - 1 ) * @size ROWS FETCH NEXT @size ROWS ONLY; ---offset的當前頁面是從零開

到此這篇關於SQL Server分頁的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: