.net中可以这样分页

CarlHui 2004-07-30 10:23 阅读:1862


在.net中可以用DataSet作为数据源,与DataGrid绑定,实现自动分页显示,这种分面在数据量枈少的情况下比校好,但当数据量大时,比如说一在论谈里,用这种方式实现效率会很底,因为自动分页时,把所有数据都从数据库中取出,速度会比较慢,为了提高效率可以采用[b]自定义分页[/b]。
现以SqlServer数据库为例,我们现想分页显示Northwind数据库中的Employees信息,可建立如下存贮过程:
CREATE PROCEDURE sp_GetEmployeesByPage
@PageNumber    int,
@PageSize    int
AS

-- create a temporary table with the columns we are interested in
CREATE TABLE #TempEmployees
(
    ID         int IDENTITY PRIMARY KEY,
    EmployeeID    int,
    LastName    nvarchar(20),
    FirstName    nvarchar(10),
    Title        nvarchar(30),
    TitleOfCourtesy    nvarchar(25),
    Address        nvarchar(60),
    City        nvarchar(15),
    Region        nvarchar(15),
    Country        nvarchar(15),
    Notes        ntext
)

-- fill the temp table with all the employees
INSERT INTO #TempEmployees
(
    EmployeeID,
    LastName,
    FirstName,
    Title,
    TitleOfCourtesy,
    Address,
    City,
    Region,
    Country,
    Notes
)
SELECT
    EmployeeID,
    LastName,
    FirstName,
    Title,
    TitleOfCourtesy,
    Address,
    City,
    Region,
    Country,
    Notes
FROM
  Employees ORDER BY EmployeeID ASC

-- declare two variables to calculate the range of records to extract for the specified page
DECLARE @FromID int
DECLARE @ToID int
-- calculate the first and last ID of the range of records we need
SET @FromID = ((@PageNumber - 1) * @PageSize) + 1
SET @ToID = @PageNumber * @PageSize

-- select the page of records
SELECT * FROM #TempEmployees WHERE ID >= @FromID AND ID <= @ToID

然后在程序时调用存贮过程sp_GetEmployeesByPage 传入每页大小,及第几页,就可以检索出指定页的记录,实现自定义分页的效果,这样操作比自动分页速度上与性能上会有明显的提升。

0条评论

登陆后可评论