分页的优化

      在学校的时候,使用gridview等控件都是在pageindexchanged方法中进行绑定,这样在数据量不大的情况下是否看不到什么影响,现在在项目中看到的在存储过程中使用方法是传两个参数:PageIndex 和PageSize,但是由于封装的好,一直没时间去看,今天又看到这个问题,于是了解了一下,下面做下笔记:

      在oracle中使用的方法尤为简单(也是今天刚知道的,呵呵)。 

 

 

    select * from
    (
      select id,username, row_number() over (order by username) as indexid
       from users) as t

    where t.indexid >=11 and indexid<=20

 

 

     上面就是使用了oralce中的over方法,得到了第二页的十条记录,此方法在sql server2005也适用,但是不是很推荐,数据量较大时,会有所影响。

   下面这个是sql server2005自带的aspnet中使用的方法, 存储过程名为:aspnet_Membership_GetAllUsers,也是我们在项目中使用的方法:

     ALTER PROCEDURE [dbo].[aspnet_Membership_GetAllUsers]
    @ApplicationName       nvarchar(256),
    @PageIndex             int,
    @PageSize              int
  AS
  BEGIN
      DECLARE @ApplicationId uniqueidentifier
      SELECT  @ApplicationId = NULL
      SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
      IF (@ApplicationId IS NULL)
          RETURN 0


      -- Set the page bounds
      DECLARE @PageLowerBound int
      DECLARE @PageUpperBound int

      DECLARE @TotalRecords   int

 

      // @PageLowerBound为要显示页面的第一条记录index

      SET @PageLowerBound = @PageSize * @PageIndex

 

     // @PageUpperBound为要显示页面最后一条记录的index

      SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

      -- Create a temp table TO store the select results

 

    //创建临时表,将所有的记录先存入此表中,它的indexID字段是自增长的.

      CREATE TABLE #PageIndexForUsers      
      (
          IndexId int IDENTITY (0, 1) NOT NULL,
          UserId uniqueidentifier
      )

  

//将记录全部存入此表中,这时根据排序所得的结果将由pageIndexForUsers表中的自增长字段固定

      此处使用了效率其高的insert into  (表名) select 方法,因为其是成块的将数据拷入到表中, 大大提高了效率.


 

    -- Insert into our temp table
    INSERT INTO #PageIndexForUsers (UserId)
    SELECT u.UserId
    FROM   dbo.aspnet_Membership m, dbo.aspnet_Users u
    WHERE  u.ApplicationId = @ApplicationId AND u.UserId = m.UserId
    ORDER BY u.UserName

    SELECT @TotalRecords = @@ROWCOUNT


  //这边通过连接临时表#PageIndexForUsers来获得所要页的记录,因为这时#PageIndexForUsers中的记录index都已固定.

    SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
            m.CreateDate,
            m.LastLoginDate,
            u.LastActivityDate,
            m.LastPasswordChangedDate,
            u.UserId, m.IsLockedOut,
            m.LastLockoutDate
    FROM   dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p
    WHERE  u.UserId = p.UserId AND u.UserId = m.UserId AND
           p.IndexId >= @PageLowerBound AND p.IndexId <= @PageUpperBound
    ORDER BY u.UserName

     上面的方法只需要通过临时表中的userID连接就可以从正式表庞大的数据中筛选出你需要的page的记录,是很大程度上提高了效率.

     笔记完毕...

 

posted @ 2008-12-08 18:44  want  阅读(430)  评论(1)    收藏  举报