Advance .Net

导航

 
数据分页会在很多地方用到,特别是在一次从数据库提取的数据量非常大时,这时对数据进行分页什么重要,如何在数据库层对数据进行分页?一般是采用数据库存储过程的方式对数据进行分页,大体思路是这样的:首先做一个存储过程,在存储过程是先提取所有的数据,然后将这些数据保存在一个临时表里面,然后再根据传入的参数(也就是第几页以及每页多少条数据)再从提出的数据中抽出所要的页即可。在这其中要用到一个数据库函数:row_number,在些我给出我曾经做过的项目中的一个分页的实例参考(开发环境为MS SQL Server Express 2005):
 1set ANSI_NULLS ON
 2set QUOTED_IDENTIFIER ON
 3GO
 4ALTER procedure [dbo].[GetProductsByDeliverReason]
 5(
 6    @deliverReason nvarchar(200),
 7    @DescriptionLength int,
 8    @PageNumber int,
 9    @ProductsPerPage int,
10    @howManyProducts int output
11)
12AS
13BEGIN
14    declare @Products table
15    (
16        RowNumber int,
17        ProductID int,
18        Name nvarchar(50),
19        Description nvarchar(1000),
20        Price money,
21        Image1FileName nvarchar(50),
22        Image2FileName nvarchar(50),
23        OnCatalogPromotion bit
24    )
25
26    declare @categoryID int
27    select @categoryID=CategoryID from DeliverReasonCategory where DeliverReason=@deliverReason
28    insert into @Products
29        select ROW_NUMBER() over (order by Product.ProductID),Product.ProductID,
30        Name,substring(Description,1,@DescriptionLength)+'' as Description,Price,
31        Image1FileName,Image2FileName,OnCatalogPromotion from Product join DeliverReasonProductCategory
32        on Product.ProductID=DeliverReasonProductCategory.ProductID 
33        where DeliverReasonProductCategory.CategoryID=@categoryID
34    
35    select @howManyProducts=count(ProductID) from @Products
36    
37    select ProductID,Name,Description,Price,Image1FileName,Image2FileName,OnCatalogPromotion
38    from @Products
39    where RowNumber>(@PageNumber-1)*@ProductsPerPage and RowNumber<=@PageNumber*@ProductsPerPage
40END
41

在此我简要的说明一下,该存储过程首先声明一个内存表变量用户保存从数据库中提取的全部数据,然后向该内存表中插入数据,注意在插入数据是多了一列,名为RowNumber,这列的值是用29行的ROW_NUMBER函数产生的。最后第37到39行取出真正想要的数据。
posted on 2008-05-07 10:54  胡振  阅读(246)  评论(0)    收藏  举报