SQL Server 2005高效分页存储过程

SQL Server 2005高效分页存储过程 ,这是在网上找到的经修改调试使用暂时没发现错误,发布在此供需要的人参考。开始那位大侠写出来可能是没有测试传条件的错误,现已经修改并加入了部分代码修正此错误。由于有人提到如何使用此代码,我是用C#语言,把把引用代码贴出来共参考吧。

代码1  存储过程源码

IF exists (SELECT * FROM dbo.sysobjects WHERE id = object_id(N‘[dbo].[proc_DataPagingList]‘) and OBJECTPROPERTY(id, N‘IsProcedure‘) = 1)
drop procedure [dbo].[proc_DataPagingList]
GO

CREATE PROCEDURE [dbo].[proc_DataPagingList]
(
@tableName NVARCHAR(200),      ----要显示的表或多个表的连接
@fieldNames NVARCHAR(200)=‘*‘, ----要显示的字段列表
@pageSize INT = 10,            ----每页显示的记录个数
@page INT = 10,                ----要显示那一页的记录
@pageCount INT = 1 output,     ----查询结果分页后的总页数
@counts INT = 1 output,        ----查询到的总记录数
@fieldSort NVARCHAR(200)= null,----排序字段列表或条件
@sort BIT = 1,                 ----排序方法,0为升序,1为降序--程序传参如:‘ SortA Asc,SortB Desc,SortC ‘)
@condition NVARCHAR(200)= null,----查询条件,不需WHERE
@keyID NVARCHAR(100),          ----主表的主键
@distinct BIT = 0              ----是否添加查询字段的 DISTINCT 默认0不添加/1添加
)
AS

SET NOCOUNT ON
Declare @SELECT NVARCHAR(1000)    ----存放动态生成的SQL语句
Declare @strCounts NVARCHAR(1000) ----存放取得查询结果总数的查询语句
Declare @strID  NVARCHAR(1000)    ----存放取得查询开头或结尾ID的查询语句

Declare @sortTypeA NVARCHAR(10)   ----数据排序规则A
Declare @SortTypeB NVARCHAR(10)   ----数据排序规则B

Declare @distSelect NVARCHAR(50)  ----对含有DISTINCT的查询进行SQL构造
Declare @distCounts NVARCHAR(50)  ----对含有DISTINCT的总数查询进行SQL构造

DECLARE @SortfieldA NVARCHAR(50)  ----对含有是否还有排序字段时的排序方式组合A
DECLARE @SortfieldB NVARCHAR(50)  ----对含有是否还有排序字段时的排序方式组合B


IF @distinct = 0
	BEGIN
		SET @distSelect = ‘SELECT ‘
		SET @distCounts = ‘ COUNT(*)‘
	END
ELSE
	BEGIN
		SET @distSelect = ‘SELECT distinct ‘
		SET @distCounts = ‘ COUNT(DISTINCT ‘+@keyID+‘)‘
	END

IF @sort=0
	BEGIN
		SET @SortTypeB=‘ ASC ‘
		SET @sortTypeA=‘ DESC ‘
	END
ELSE
	BEGIN
		SET @SortTypeB=‘ DESC ‘
		SET @sortTypeA=‘ ASC ‘
	END

IF @fieldSort IS NOT NULL AND @fieldSort<>‘‘ --排序字段不为空时
	BEGIN
		SET @SortfieldB=‘ order by ‘+ @fieldSort +‘ ‘+ @SortTypeB
		SET @SortfieldA=‘ order by ‘+ @fieldSort +‘ ‘+ @SortTypeA 
	END
ELSE
	BEGIN
		SET @SortfieldB=‘‘
		SET @SortfieldA=‘‘
	END

--------生成查询语句--------
--此处@strCounts为取得查询结果数量的语句
IF @condition is null or @condition=‘‘     --没有设置显示条件
	BEGIN
		SET @SELECT =  @fieldNames + ‘ FROM ‘ + @tableName
		SET @strCounts = @distSelect+‘ @counts=‘+@distCounts+‘ FROM ‘+@tableName
		SET @strID = ‘ FROM ‘ + @tableName
	END
ELSE
	BEGIN
		SET @SELECT = + @fieldNames + ‘FROM ‘ + @tableName + ‘ WHERE  ‘ + @condition
		SET @strCounts = @distSelect+‘ @counts=‘+@distCounts+‘ FROM ‘+@tableName + ‘ WHERE ‘ + @condition
		SET @strID = ‘ FROM ‘ + @tableName + ‘ WHERE  ‘ + @condition
	END

----取得查询结果总数量-----
exec sp_executesql @strCounts,N‘@counts INT out ‘,@counts out
DECLARE @tmpCounts INT

IF @counts = 0
    SET @tmpCounts = 1
ELSE
    SET @tmpCounts = @counts

    --取得分页总数
    SET @pageCount=(@tmpCounts+@pageSize-1)/@pageSize

    --/**当前页大于总页数 取最后一页**/
    IF @page>@pageCount
        SET @page=@pageCount

    --/*-----数据分页2分处理-------*/
    DECLARE @pageIndex INT --总数/页大小
    DECLARE @lastcount INT --总数%页大小 

    SET @pageIndex = @tmpCounts/@pageSize
    SET @lastcount = @tmpCounts%@pageSize
    IF @lastcount > 0
        SET @pageIndex = @pageIndex + 1
    ELSE
        SET @lastcount = @pageSize

    --显示分页
    IF @condition is null or @condition=‘‘     --没有设置显示条件
    BEGIN
        IF @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2   --前半部分数据处理
            BEGIN 
                SET @strCounts=@distSelect+‘ TOP ‘+ CAST(@pageSize as VARCHAR(4))+‘ ‘+ @fieldNames+‘ FROM ‘+@tableName + ‘ WHERE ‘+@keyID+‘ not in(‘+ @distSelect+‘ TOP ‘+ CAST(@pageSize*(@page-1) as Varchar(20)) +‘ ‘+ @keyID +‘ FROM ‘+@tableName + @SortfieldB +‘)‘ + @SortfieldB 
            END
        ELSE
            BEGIN
            SET @page = @pageIndex-@page+1 --后半部分数据处理
                IF @page <= 1 --最后一页数据显示
                    SET @strCounts=@distSelect+‘ * FROM (‘+@distSelect+‘ TOP ‘+ CAST(@lastcount as VARCHAR(4))+‘ ‘+ @fieldNames+‘ FROM ‘+@tableName + @SortfieldA+‘) AS TempTB ‘+@SortfieldB
                ELSE                
                    SET @strCounts=@distSelect+‘ * FROM (‘+@distSelect+‘ TOP ‘+ CAST(@pageSize as VARCHAR(4))+‘ ‘+ @fieldNames+‘ FROM ‘+@tableName + ‘ WHERE ‘+@keyID+‘ not in(‘+ @distSelect+‘ TOP ‘+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +‘ ‘+ @keyID +‘ FROM ‘+@tableName + @SortfieldA+‘)‘ + @SortfieldA+‘) AS TempTB ‘+@SortfieldB
            END
    END

    ELSE --有查询条件
    BEGIN
        IF @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2   --前半部分数据处理
        BEGIN 
                SET @strCounts=@distSelect+‘ TOP ‘+ CAST(@pageSize as VARCHAR(4))+‘ ‘+ @fieldNames +‘ FROM  ‘+@tableName + ‘ WHERE ‘+@keyID+‘ not in(‘+ @distSelect+‘ TOP ‘+ CAST(@pageSize*(@page-1) as Varchar(20)) +‘ ‘+ @keyID +‘ FROM ‘+@tableName + ‘ Where ‘ + @condition + @SortfieldB+‘)‘+‘ AND ‘ + @condition + @SortfieldB                 
        END
        ELSE
        BEGIN 
            SET @page = @pageIndex-@page+1 --后半部分数据处理
            IF @page <= 1 --最后一页数据显示
                    SET @strCounts=@distSelect+‘ * FROM (‘+@distSelect+‘ TOP ‘+ CAST(@lastcount as VARCHAR(4))+‘ ‘+ @fieldNames+‘ FROM ‘+@tableName + ‘ WHERE  ‘+ @condition +@SortfieldA+‘) AS TempTB ‘+@SortfieldB
            ELSE
                    SET @strCounts=@distSelect+‘ * FROM (‘+@distSelect+‘ TOP ‘+ CAST(@pageSize as VARCHAR(4))+‘ ‘+ @fieldNames+‘ FROM ‘+@tableName + ‘ WHERE ‘+@keyID+‘ not in(‘+ @distSelect+‘ TOP ‘+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +‘ ‘ + @keyID +‘ FROM ‘+@tableName +‘ WHERE  ‘+ @condition +@SortfieldA+‘)‘ +‘ AND ‘+ @condition +@SortfieldA+‘) AS TempTB ‘ + @SortfieldB 
        END    
    END

------返回查询结果-----
exec sp_executesql @strCounts
SET NOCOUNT OFF 

代码2  C#后台调用代码

//调用以下必须先创建一个DataPageList 对象,用引用型传递这个对象来访问以下GetDataPageList函数,并返回DataPageList 对象。这个返回的对象中包括很多属性,直接引用需要的属性即可,见属性类介绍。
       private static readonly string mConnectionString = ConfigurationManager.ConnectionStrings["FleaMarketConnString"].ConnectionString;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dpl"></param>
        /// <returns></returns>
        public DataPageList GetDataPageList(ref DataPageList dpl)
        {
            SqlConnection conn = new SqlConnection(mConnectionString);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand();
            da.SelectCommand.Connection = conn;
            da.SelectCommand.CommandText = "proc_DataPagingList";
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@tableName", SqlDbType.NVarChar, 200).Value = dpl.TableName;
            da.SelectCommand.Parameters.Add("@fieldNames", SqlDbType.NVarChar, 200).Value = dpl.FieldNames;
            da.SelectCommand.Parameters.Add("@pageSize", SqlDbType.Int).Value = dpl.PageSize;
            da.SelectCommand.Parameters.Add("@page", SqlDbType.Int).Value = dpl.Page;
            da.SelectCommand.Parameters.Add("@pageCount", SqlDbType.Int).Direction = ParameterDirection.Output;
            da.SelectCommand.Parameters.Add("@counts", SqlDbType.Int).Direction = ParameterDirection.Output;
            da.SelectCommand.Parameters.Add("@fieldSort", SqlDbType.NVarChar, 100).Value = dpl.FieldSort;
            da.SelectCommand.Parameters.Add("@sort", SqlDbType.Bit).Value = dpl.Sort;
            da.SelectCommand.Parameters.Add("@condition", SqlDbType.NVarChar, 200).Value = dpl.Condition;
            da.SelectCommand.Parameters.Add("@keyID", SqlDbType.NVarChar, 100).Value = dpl.KeyID;
            da.SelectCommand.Parameters.Add("@Distinct", SqlDbType.Bit).Value = dpl.Distinct;
            DataSet ds = new DataSet();
            da.Fill(ds);
            //PageListReturnValue plr = new PageListReturnValue();
            dpl.GetDataSet = ds;
            dpl.Counts = int.Parse(da.SelectCommand.Parameters["@counts"].Value.ToString());
            dpl.PageCount = int.Parse(da.SelectCommand.Parameters["@pageCount"].Value.ToString());
            //object[] obj = new object[3];
            //obj[0] = ds;
            //obj[1] = da.SelectCommand.Parameters["@counts"].Value;
            //obj[2] = da.SelectCommand.Parameters["@pageCount"].Value;
            return dpl;
        }


代码3 属性实体代码

/// <summary>
    /// 高效分页输出输入参数属性
    /// </summary>
    public class DataPageList
    {
        private int _page=1;//第多少页
        private int _pageSize = 10;//请求页面大小

        
        private string _jsonRowsName = "rows";

        private string _tableName = "";
        private string _fieldNames = "*";//默认为所有数据
        private string _fieldSort = "";
        private byte _sort = 1;
        private string _condition = "";
        private string _keyID = "";
        private byte _distinct = 0;
        
        private int _counts = 10;//总页数
        private int _pageCount = 10;//总的多少页面
        private DataSet _dataset = null;
        /// <summary>
        /// 总记录数
        /// </summary>
        public int Counts
        {
            get { return _counts; }
            set { _counts = value; }
        }
        /// <summary>
        /// 总分页数
        /// </summary>
        public int PageCount
        {
            get { return _pageCount; }
            set { _pageCount = value; }
        }
        /// <summary>
        /// 数据集
        /// </summary>
        public DataSet GetDataSet
        {
            get { return _dataset; }
            set { _dataset = value; }
        }


        /// <summary>
        /// 第几页
        /// </summary>
        public int Page
        {
            get { return _page; }
            set { _page = value; }
        }
        /// <summary>
        /// 每页显示的记录数
        /// </summary>
        public int PageSize
        {
            get { return _pageSize; }
            set { _pageSize = value; }
        }
        /// <summary>
        /// Flexigrid Json行名,固定为rows
        /// </summary>
        public string JsonRowsName
        {
            get { return _jsonRowsName; }
            //set { _jsonRowsName = value; }
        }

        /// <summary>
        /// 表名或视图名称
        /// </summary>
        public string TableName
        {
            get { return _tableName; }
            set { _tableName = value; }
        }

        /// <summary>
        /// 字段名,默认为*
        /// </summary>
        public string FieldNames
        {
            get { return _fieldNames; }
            set { _fieldNames = value; }
        }

        /// <summary>
        /// 排序字段
        /// </summary>
        public string FieldSort
        {
            get { return _fieldSort; }
            set { _fieldSort = value; }
        }

        /// <summary>
        /// 排序方式,默认为1,表示降序;0表示升序
        /// </summary>
        public byte Sort
        {
            get { return _sort; }
            set { _sort = value; }
        }

        /// <summary>
        /// 查询条件,不加where
        /// </summary>
        public string Condition
        {
            get { return _condition; }
            set { _condition = value; }
        }

        /// <summary>
        /// 表主键
        /// </summary>
        public string KeyID
        {
            get { return _keyID; }
            set { _keyID = value; }
        }

        /// <summary>
        /// 是否消除记录重复,同时包括计数,默认0表示不添加
        /// </summary>
        public byte Distinct
        {
            get { return _distinct; }
            set { _distinct = value; }
        }
    }


SQL Server 2005高效分页存储过程,布布扣,bubuko.com

SQL Server 2005高效分页存储过程

上一篇:sqlserver中的全局变量


下一篇:Photoshop为秋季外景人物调制出清爽的暖色调