ASP.NET技巧:在預存程序中實現分頁

來源:互聯網
上載者:User
asp.net|預存程序|分頁|技巧     我不是一個很有經驗的程式員,在做項目的過程中會遇到很多的問題,在資料庫中使用分頁就是我做項目中遇到的一個問題.我從網上查了很多資料,有很多種方法.但我覺的建立臨時資料表是最簡單的方法,在我做Membership擴充時發現原來微軟也是這樣用的,你可一隨便開啟一個Membership的預存程序看看.
     說了再多也沒用,只要看看代碼就清楚了,呵呵.
    
 1CREATE PROCEDURE dbo.CreateSimple
 2(
 3 @PageIndex int,
 4 @PageSize int
 5)
 6AS
 7BEGIN
 8 --定義三個變數:
 9 -- @PageLowerBound :所取出記錄的下限.
10 -- @PageUpperBound: 所要取出記錄的上限.
11 -- @TotalRecords: 返回記錄總數,主要用於頁面的計算.
12 DECLARE @PageLowerBound int
13 DECLARE @PageUpperBound int
14 DECLARE @TotalRecords int
15
16 --計算上下限的值.
17 SET @PageLowerBound=@PageIndex * @PageSize
18 SET @PageUpperBound=@PageLowerBound+@PageSize-1
19
20--建立暫存資料表:
21--IndexId是標識,自動成長1;
22--SimpleId由資料表[Simple]填充;
23 CREATE TABLE #PageIndexForSimple
24 (
25  IndexId int identity(0,1) NOT NULL,
26  SimpleId int
27 )
28--填充暫存資料表
29  INSERT INTO #PageIndexForSimple(SimpleId)
30  SELECT s.[SimpleId]
31  FROM [Simple] s
32  --這裡可以加WHERE condition和ODER BY語句
33 
34  --取得記錄總數,其實影響行數就是記錄總數
35  SELECT @TotalRecords=@@ROWCOUNT
36
37  --擷取我們所要的記錄.
38  SELECT s.*
39  FROM [Simple] s,#PageIndexForSimple p
40  WHERE s.[SimpleId]=p.[SimpleId]
41            AND p.[IndexId]>=@PageLowerBound
42            AND P.[IndexId]<=@PageUpperBound
43  ORDER BY s.[Simple]
44
45   --返回記錄總數.
46   RETURE @TotalRecords
47END      由上面的注釋就能看懂了,呵呵,既然寫到這裡也把程式的代碼寫出來:
 1Public List<Simple> GetSimple(int pageIndex,int pageIndex,out int totalRecords){
 2  List<Simple> entity=new List<Simple>();
 3  SqlParameter[]param=new SqlParameter[]{
 4     new SqlParameter("@PageIndex",SqlDbType.Int),
 5     new SqlParameter("@PageSize",SqlDbType.Int),
 6   new SqlParameter("@ReturnValue",SqlDbType.Int),
 7 };
 8  param[0].Value=pageIndex;
 9  param[1].Value=pageSize;
10  param[2].Direction = ParameterDirection.ReturnValue;
11  SqlDataReader reader=SqlHelper.ExecuteReader(CommandType.StoredProcedure, "GetSimple", param);
12  While(reader.Read()){
13   entity.Add(GetSimpleEntity(reader))
14  }
15  reader.Close();
16  try{
17       totalRecords=(int)param[2].Value;
18  }catch{}
19  return entity;
20}    上面的一些函數是自己寫的:
     SqlHelper類:簡化資料庫查詢類.
    GetSimpleEntity(SqlDataReader reader):由於經常在項目中會用到好基礎實體類的擷取,所以單獨寫一個私人函數,以便重用;
    值得注意的是擷取總的記錄數時可能類型為DbNull而導致錯誤.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.