對于非常大的資料模型而言,分頁檢索時,每次都加載整個資料源非常浪費。通常的選擇是檢索頁面大小的塊區的資料,而非檢索所有的資料,然後單步執行目前行。
本文示範ASP.net的DataGrid和Sql Server 實作大資料量下的分頁,為了便于實作示範,資料表采用了Northwind資料庫的Orders表(830條記錄)。
如果資料表中有唯一的自增索引,并且這個字段沒有出現斷号現象。檢索頁面大小的塊區資料就非常簡單了。通過簡單的Sql語句就可以實作這個功能:
select * from orders where orderid between 10248 and 10253
其中,開始編号為:(CurrentPageIndex - 1) * PageSize 結束編号為:CurrentPageIndex * PageSize
當然,如果這個字段斷号不是很嚴重,而且允許不是很嚴格的按照每頁條數分頁,這樣的方法也是可以用的。
如果這個字段斷号,或者需要按照其他條件排序分頁,就要複雜些了。首先要獲得這個頁面需要顯示的編号,然後再按照這個編号獲得需要的塊區資料。根據編号獲得塊區資料很簡單。不過用下面方式獲得資料排序并不是按照指定的id清單順序,這時候還要附加order by 指令。
select * from orders where orderid in (10248,10249,10250,10251,10252,10253) order by orderid desc
獲得這個頁面需要顯示的編号清單就複雜多了,而且有多種方案:
方案一:維護一個表,這個表記錄需要顯示的這些編号排序順序。(這個表可以是臨時表,也可以是實體表)。下面示範了利用一個全局臨時表。這個全局臨時表記錄需要顯示的編号。注意排序,這裡的order by 就是需要顯示的排序順序。
create table ##temptable(
iid int IDENTITY (1, 1) NOT NULL,
mainid int NOT NULL
)
insert ##temptable(mainid) select OrderID from orders order by OrderID desc
select * from ##temptable
drop table ##temptable -- 實際執行時候,删除全部臨時表當然不再這裡執行。
這個臨時表存在,獲得指定分頁的分塊資料就很簡單了。看下面代碼:
create table ##temptable(iid int IDENTITY (1, 1) NOT NULL,mainid int NOT NULL)
insert ##temptable(mainid) select OrderID from orders order by OrderID desc
declare @PageSize int,@CurrPage int,@strSQL varchar(2000),@IDStr varchar(1000)
select @PageSize = 30
select @CurrPage = 2
select @IDStr = ''
select @IDStr = @IDStr + ltrim(rtrim(str(MainID))) + ',' from ##temptable
where iid between ((@CurrPage-1)*@PageSize+1) and @CurrPage*@PageSize
if @IDStr <> ''
begin
select @IDStr = left(@IDStr,len(@IDStr)-1)
end
select @strSQL = 'select * from orders where OrderID in ('[email protected]+') order by OrderID desc '
exec(@strSQL)
drop table ##temptable
注意:實際使用這個方案的時候,還要考慮何時更新這個全局臨時表,一般是放到計劃任務中,定時更新這個彙總表。
方案二:每次都去查詢,每次獲得最新的編号順序。由于這時候不存在這個臨時表,書寫獲得需要顯示頁面的編号的字元串就需要點技巧,看下面的代碼:
declare @PageSize int,@CurrPage int,
@topnum int,@previous int
select @PageSize = 30
select @CurrPage = 2
select @topnum = @CurrPage * @PageSize
select @previous = (@CurrPage - 1) * @PageSize
declare @i int,@IDStr nvarchar(500),@strSQL nvarchar(1000)
select @i = 0
select @strSQL = N''
select @strSQL = @strSQL + N' select top '+str(@topnum)+ ' @i = @i + 1 '
select @strSQL = @strSQL + N', @IdStr = '
select @strSQL = @strSQL + N'case when @i > '+str(@previous)+' then @IdStr + ltrim(rtrim(str(OrderID))) + '','' '
select @strSQL = @strSQL + N'else N''''end '
select @strSQL = @strSQL + N'from Orders '
select @strSQL = ltrim(rtrim(@strSQL)) + N' order by OrderID desc '
Select @IdStr = N''
exec sp_executesql @strSQL,N'@i int,@IdStr varchar(500) output',@i,@IdStr output
if len(rtrim(ltrim(@IdStr))) > 0
begin
select @IdStr = left(@IdStr,len(@IdStr)-1)
end
select @strSQL = 'select * from orders where OrderID in ('[email protected]+')'
exec(@strSQL)
asp.net 的 DataGrid 提供了使用這種分區的資料的方法。 DataGrid 通過 AllowCustomPaging 和 VirtualItemCount 屬性支援塊區操作。如果 AllowCustomPaging 為 true,則 DataGrid 不會根據 CurrentPageIndex 計算資料模型中的起始顯示位置。DataGrid 将顯示資料模型中的所有資料,而頁導航欄将目前位置報告為 (VirtualItemCount+PageSize-1)/PageSize 之 CurrentPageIndex 頁。下面的示例說明此功能。
protected void BindDataGrid(int currpage)
{
string strConn = "Data Source=(local);Integrated Security=SSPI;database=Northwind";
// 請确認 機器名/ASPNET 使用者可以通路Northwind資料庫
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(strConn);
SqlParameter[] parms = new SqlParameter[] {
new SqlParameter("@PageSize",SqlDbType.Int),
new SqlParameter("@CurrPage",SqlDbType.Int),
new SqlParameter("@SearchSql",SqlDbType.NVarChar,128),
new SqlParameter("@Count",SqlDbType.Int),
};
parms[0].Value = DataGrid1.PageSize;
parms[1].Value = (currpage+1);
// 資料庫的分頁算法第一頁是1 DataGrid的第一頁是0
parms[2].Value = DBNull.Value;
parms[3].Direction = ParameterDirection.Output;
parms[3].Value = DBNull.Value;
DataSet DS = new DataSet();
try
{
if (conn.State != ConnectionState.Open) conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Selected_Page_List";
cmd.CommandType = CommandType.StoredProcedure;
if (parms != null)
{
foreach (SqlParameter parm in parms)
cmd.Parameters.Add(parm);
}
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
int aa = Convert.ToInt32(parms[3].Value.ToString());
cmd.Parameters.Clear();
if (currpage == 0)
{
DataGrid1.VirtualItemCount = aa;
}
DataGrid1.CurrentPageIndex = currpage;
DataGrid1.DataSource = DS;
DataGrid1.DataBind();
}
catch(Exception ewx)
{
conn.Close();
Response.Write (ewx.Message.ToString());
Response.End();
}
}
void Page_Load(Object sender, EventArgs E ) {
if (!IsPostBack)
{
BindDataGrid(0);
// 第一次打開這個頁面,通路分頁的第一頁
}
}
void MyDataGrid_Page(Object sender, DataGridPageChangedEventArgs e) {
BindDataGrid(e.NewPageIndex);
}
如果你有更多資料量的表稍加修改,也可以使用本示範程式。其下是示範代碼下載下傳,示範代碼使用的是方案二。使用方法看readme.txt檔案。
整個示範代碼 下載下傳
http://chs.gotdotnet.com/quickstart/aspplus/samples/webforms/ctrlref/webctrl/datagrid/doc_datagrid.aspx#paging
這裡示範了利用DataGrid 的這個功能(沒有本文中讨論的利用存儲過程獲得分區資料)。如對DataGrid的這個功能不太熟悉,請先看這裡。