我不是一個(gè)很有經(jīng)驗(yàn)的程序員,在做項(xiàng)目的過(guò)程中會(huì)遇到很多的問(wèn)題,在數(shù)據(jù)庫(kù)中使用分頁(yè)就是我做項(xiàng)目中遇到的一個(gè)問(wèn)題.我從網(wǎng)上查了很多資料,有很多種方法.但我覺(jué)的創(chuàng)建臨時(shí)數(shù)據(jù)表是最簡(jiǎn)單的方法,在我做membership擴(kuò)展時(shí)發(fā)現(xiàn)原來(lái)微軟也是這樣用的,你可一隨便打開(kāi)一個(gè)membership的存儲(chǔ)過(guò)程看看.
說(shuō)了再多也沒(méi)用,只要看看代碼就清楚了,呵呵.
1create procedure dbo.createsimple
2(
3 @pageindex int,
4 @pagesize int
5)
6as
7begin
8 --定義三個(gè)變量:
9 -- @pagelowerbound :所取出記錄的下限.
10 -- @pageupperbound: 所要取出記錄的上限.
11 -- @totalrecords: 返回記錄總數(shù),主要用于頁(yè)面的計(jì)算.
12 declare @pagelowerbound int
13 declare @pageupperbound int
14 declare @totalrecords int
15
16 --計(jì)算上下限的值.
17 set @[email protected] * @pagesize
18 set @[email protected][email protected]
19
20--創(chuàng)建臨時(shí)表:
21--indexid是標(biāo)識(shí),自動(dòng)增長(zhǎng)1;
22--simpleid由數(shù)據(jù)表[simple]填充;
23 create table #pageindexforsimple
24 (
25 indexid int identity(0,1) not null,
26 simpleid int
27 )
28--填充臨時(shí)表
29 insert into #pageindexforsimple(simpleid)
30 select s.[simpleid]
31 from [simple] s
32 --這里可以加where condition和oder by語(yǔ)句
33
34 --取得記錄總數(shù),其實(shí)影響行數(shù)就是記錄總數(shù)
35 select @[email protected]@rowcount
36
37 --獲取我們所要的記錄.
38 select s.*
39 from [simple] s,#pageindexforsimple p
40 where s.[simpleid]=p.[simpleid]
41 and p.[indexid]>[email protected]
42 and p.[indexid]<[email protected]
43 order by s.[simple]
44
45 --返回記錄總數(shù).
46 reture @totalrecords
47end 由上面的注釋就能看懂了,呵呵,既然寫(xiě)到這里也把程序的代碼寫(xiě)出來(lái):
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} 上面的一些函數(shù)是自己寫(xiě)的:
sqlhelper類:簡(jiǎn)化數(shù)據(jù)庫(kù)查詢類.
getsimpleentity(sqldatareader reader):由于經(jīng)常在項(xiàng)目中會(huì)用到好基礎(chǔ)實(shí)體類的獲取,所以單獨(dú)寫(xiě)一個(gè)私有函數(shù),以便重用;
值得注意的是獲取總的記錄數(shù)時(shí)可能類型為dbnull而導(dǎo)致錯(cuò)誤.