日期:2008-10-02  浏览次数:20457 次

先在数据库中定义存储过程,轻易实现百万级数据分页:
//@PageSize:分页大小,PageIndex:页号,@PageCount:总页数,@recordCount:记录数
CREATE PROCEDURE GetCustomDataPage @pageSize int, @pageIndex int, @pageCount int output, @recordCount int output AS
declare @SQL varchar(1000)
select @recordCount=count(*) from products
set @pageCount=ceiling(@recordCount*1.0/@pageSize)
if @pageIndex = 0 or @pageCount<=1
set @SQL='select top '+str(@pageSize)+' productID,productName, unitPrice from products order by productID asc'
else if @pageIndex = @pageCount -1
 set @SQL='select * from ( select top '+str(@recordCount - @pageSize * @pageIndex)+' productID,productName, unitPrice from products order by productID desc) TempTable order by productID asc'

else  set @SQL='select top '+str(@pageSize) +' * from ( select top '+str(@recordCount - @pageSize * @pageIndex)+' productID,productName, unitPrice from products order by productID desc) TempTable order by productID asc'

exec(@SQL)
GO
好了,存储过程建好了,那么如何在.Net中使用呢?请看以下代码:

        private uint pageCount;  //总页数

        private uint recordCount;  //总记录数

        private DataSet GetPageData(uint pageSize, uint pageIndex)

        {

            string strConn = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];           

            SqlConnection conn = new SqlConnection(strConn);

            conn.Open();

            SqlCommand command = new SqlCommand("GetCustomDataPage",conn);  //第一个参数为存储过程名

            command.CommandType = CommandType.StoredProcedure;   //声明命令类型为存储过程

            command.Parameters.Add("@pageSize",SqlDbType.Int);

            command.Parameters["@pageSize"].Value = pageSize;

            command.Parameters.Add("@pageIndex",SqlDbType.Int);

            command.Parameters["@pageIndex"].Value = pageIndex;

            command.Parameters.Add("@pageCount",SqlDbType.Int);

            command.Parameters["@pageCount"].Value = pageCount;

            command.Parameters["@pageCount"].Direction = ParameterDirection.Output;  //存储过程中的输出参数