萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> sql server教程 >> 毫秒級百萬數據分頁存儲過程

毫秒級百萬數據分頁存儲過程

今天把我使用的分頁代碼繼續分享,首先參考園子裡的高手方法生成一個百萬數據表; 耗時 33 秒;

然後創建分頁存儲過程;這個是基於SQL 2005 的ROW_NUMBER的, SQL 2000 不適用; SQL 2008 我沒有安裝,所以也沒有測試過!估計應該可以運行.

 2種算法可以選擇 1. 使用  BETWEEN   ;  2.  TOP  ; 代碼中已經注釋了.

我測試了一下2種方法基本沒有什麼區別;代碼如下:

USE [DATA_TEMP]
GO
/****** 對象:  StoredProcedure [dbo].[im531_Page]    腳本日期: 11/26/2010 10:52:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:  im531
-- Create date: 2010-10-25
-- Description: SQL 2005 ROW_NUMBER 分頁
-- Modify Date: 2010-10-26
-- =============================================

CREATE PROCEDURE [dbo].[im531_Page]
 @TabeName AS NVARCHAR(50),
 @Fields AS NVARCHAR(1024),
 @SearchWhere AS NVARCHAR(1024),
 @OrderFields AS NVARCHAR(1024),
 @pageNumber AS INT,
 @page AS INT
AS
BEGIN
 SET NOCOUNT ON;
 DECLARE @sqlType AS TINYINT
 SET @sqlType = 0  -- 0 BETWEEN  1 TOP
 DECLARE @sql AS NVARCHAR(MAX)
 IF @SearchWhere <> '' SET @SearchWhere = ' WHERE ' + @SearchWhere
 IF @page < 2 SET @page = 1
 IF @page = 1
  BEGIN
   SET @sql = 'SELECT TOP ' + CONVERT(NVARCHAR(20),@pageNumber) + ' ' + @Fields
    + 'FROM [' + @TabeName + '][a] WITH(NOLOCK) ' + @SearchWhere + ' ORDER BY ' + @OrderFields
  END
 ELSE
  BEGIN
   --臨時表
   SET @sql = ';WITH [Page_____Table] AS('
    + 'SELECT ROW_NUMBER() OVER(ORDER BY ' + @OrderFields + ') AS [RowNow],' + @Fields
    + 'FROM ['+ @TabeName +' ][a] WITH(NOLOCK) ' + @SearchWhere
    + ')'
   --查找當前頁面記錄
   IF @sqlType = 0
    BEGIN
    -- A USE BETWEEN
     SET @sql = @sql + 'SELECT *'
      + 'FROM [Page_____Table] WITH(NOLOCK)'
      + 'WHERE [RowNow] BETWEEN ' + CONVERT(NVARCHAR(20),(@page - 1) * @pageNumber + 1) + ' AND ' + CONVERT(NVARCHAR(20),@page * @pageNumber)
      + 'ORDER BY [RowNow]'
    END
   ELSE
    BEGIN
    -- B USE TOP
     SET @sql = @sql + 'SELECT TOP ' + CONVERT(NVARCHAR(20),@pageNumber) + ' *'
      + 'FROM [Page_____Table] WITH(NOLOCK)'
      + 'WHERE [RowNow] > ' + CONVERT(NVARCHAR(20),(@page - 1) * @pageNumber)
      + 'ORDER BY [RowNow]'
    END
  END
 EXEC(@sql)
END

然後測試分頁性能;每頁顯示20條記錄, 百萬數據最大50000頁,當前頁采用隨機數取值;

DECLARE @d DATETIME
SET @d = GETDATE()

DECLARE @M AS INT;DECLARE @N AS INT;DECLARE @cPage AS INT
SET @M = 50000;SET @N = 1
SET @cPage = CAST((rand()*(@M-@N)+@N) AS INT)

EXECUTE [im531_Page]
 @TabeName = 'Table_1',
 @Fields = '[a],[b]',
 @SearchWhere = '[a] > 0',
 @OrderFields = '[a] DESC',
 @pageNumber = 20,
 @page = @cPage


SELECT [當前頁] = @cPage,[分頁執行耗時間(毫秒)] = DATEDIFF(ms,@d,GETDATE())

在我的機器上面測試均為毫秒級!!!!

園子裡的高手若有更好的方法歡迎分享一下!!!!!!!!!!!!!!!

關鍵詞:分頁  存儲過程 

copyright © 萬盛學電腦網 all rights reserved