(原创)千万数据级通用分页存储过程

兼容SQL Server2000/2005/2008/2014

直接贴代码出来

 

/*
=============================================
Author:		 chenlong
Create date: 2015-09-01
Description: 千万级分页存储过程
			 经测试11439088记录.每页15条.第8页.执行0.14s
=============================================
*/
ALTER PROCEDURE [dbo].[OPPO_Pagination]
    (
      @TableName VARCHAR(MAX) ,
      @FieldStr NVARCHAR(MAX) = '*' ,
      @OrderByFeild VARCHAR(500) = '' ,
      @WhereStr NVARCHAR(MAX) = '' ,
      @PageIndex INT = 1 ,
      @PageSize INT = 10 ,
      @RecordCount INT OUTPUT
    )
AS
    BEGIN
        SET NOCOUNT ON
        DECLARE @Sql NVARCHAR(MAX) = ''
        DECLARE @Order VARCHAR(500)= ''
 
        SET @RecordCount = 0 
        DECLARE @Where NVARCHAR(MAX) = ''
        IF @WhereStr <> ''
            BEGIN	
                SET @Where = ' WHERE ' + @WhereStr 
            END	
        SET @Sql = @Sql + ' SELECT @Totals=COUNT(1) FROM (SELECT 1 One FROM '
            + @TableName + ' ' + @Where + ') T'
            
        EXEC sp_executesql @Sql, N'@Totals INT OUT', @RecordCount OUT
		
        IF @OrderByFeild <> ''
            BEGIN
                SET @Order = ' ORDER BY ' + @OrderByFeild 
            END
        IF @PageIndex = 1
            BEGIN
                IF ( @WhereStr <> '' )
                    BEGIN
                        SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' '
                            + @FieldStr + ' FROM ' + @TableName + ' WHERE '
                            + @WhereStr + @Order 
                    END
                ELSE
                    BEGIN
                        SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' '
                            + @FieldStr + ' FROM ' + @TableName + ' ' + @Order 
                    END
            END
        ELSE
            BEGIN
                SET @Sql = 'SELECT TOP ' + STR(@PageIndex * @PageSize)
                    + ' IDENTITY(INT,1,1) AS TmpIID, ' + @FieldStr
                    + ' INTO #tmpRecord FROM ' + @TableName 
                IF ( @WhereStr <> '' )
                    BEGIN
                        SET @Sql = @Sql + ' WHERE ' + @WhereStr + @Order 
                    END
                ELSE
                    BEGIN
                        SET @Sql = @Sql + @Order 
                    END
                SET @Sql = @Sql
                    + ' SELECT * FROM #tmpRecord WITH(NOLOCK) WHERE TmpIID > '
                    + STR(( @PageIndex - 1 ) * @PageSize)
                    + ' DROP TABLE #tmpRecord'
            END
 
        PRINT @Sql 
        EXEC (@Sql)
        SET NOCOUNT OFF
    END	

  

posted on 2015-12-01 18:06  _蝶恋花 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dielianhua/articles/SQLServer_4.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值