SQL Server 2008 分页存储过程

在用的,已经不知道出处了,如果有侵权请告诉我,我立刻删掉。

USE [ActivaOnlineSupport]

GO

/****** Object: StoredProcedure [dbo].[PROCE_PAGECHANGE] Script Date: 08/13/2014 13:45:17 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[PROCE_PAGECHANGE] ( @TableName varchar(50),            --表名

 @ReFieldsStr varchar(200) = '*',   --字段名(全部字段为*)

 @OrderString varchar(200),         --排序字段(必须!支持多字段不用加order by)

 @WhereString varchar(500) =N'',  --条件语句(不用加where)

 @PageSize int,                     --每页多少条记录

 @PageIndex int = 1 ,               --指定当前为第几页

 @TotalRecord int output            --返回总记录数

) AS

  

BEGIN    

 

    --处理开始点和结束点

    Declare @StartRecord int; Declare @EndRecord int; Declare @TotalCountSql nvarchar(500); Declare @SqlString nvarchar(2000); set @StartRecord = (@PageIndex-1)*@PageSize + 1

    set @EndRecord = @StartRecord + @PageSize - 1 

    SET @TotalCountSql= N'select @TotalRecord = count(*) from ' + @TableName;--总记录数语句

    SET @SqlString = N'(select row_number() over (order by '+ @OrderString +') as rowId,'+@ReFieldsStr+' from '+ @TableName;--查询语句

    --     IF (@WhereString! = '' or @WhereString!=null) BEGIN

            SET @TotalCountSql=@TotalCountSql + ' where '+ @WhereString; SET @SqlString =@SqlString+ ' where '+ @WhereString; END

    --第一次执行得到

    --IF(@TotalRecord is null)

    -- BEGIN

           EXEC sp_executesql @totalCountSql,N'@TotalRecord int out',@TotalRecord output;--返回总记录数

    -- END

    ----执行主语句

    set @SqlString ='select * from ' + @SqlString + ') as t where rowId between ' + ltrim(str(@StartRecord)) + ' and ' +  ltrim(str(@EndRecord)); Exec(@SqlString) END

 使用方法:

private static DataSet GetListByPageByWhere(int PageSize, int PageIndex, string strWhere, string order,string sort)

{

     SqlParameter[] parameters = new SqlParameter[]

    {

        new SqlParameter("@TableName", SqlDbType.VarChar, 50), 

        new SqlParameter("@ReFieldsStr", SqlDbType.VarChar, 200),

        new SqlParameter("@OrderString", SqlDbType.VarChar, 200), 

        new SqlParameter("@WhereString", SqlDbType.VarChar, 500),

        new SqlParameter("@PageSize", SqlDbType.Int),

        new SqlParameter("@PageIndex", SqlDbType.Int),

        new SqlParameter("@TotalRecord", SqlDbType.Int)

    };



    parameters[0].Value = "ApplyItemNo";

    parameters[1].Value = "*";

    parameters[2].Value = sort + " " + order;

    parameters[3].Value = strWhere;

    parameters[4].Value = PageSize;

    parameters[5].Value = PageIndex;

    parameters[6].Value = 1;

    

    return DBHelperSQL.RunProcedure("PROCE_PAGECHANGE", parameters, "ds");

}

 

DataSet ds = GetListByPageByWhere(rows, page, strWhere, order, sort);

 

你可能感兴趣的:(SQL Server 2008)