毫秒级百万数据分页存储历程[MSSQL防范]
本文“毫秒级百万数据分页存储历程[MSSQL防范]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
本日把我利用的分页代码持续分享,首先参考园子里的高手办法生成一个百万数据表; 耗时 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())
在我的机械上面测试均为毫秒级!!!!
园子里的高手若有更好的办法欢送分享一下!!!!!!!!!!!!!!!
以上是“毫秒级百万数据分页存储历程[MSSQL防范]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |