首页 > 数据库

在数据层实现分页技术

时间:2009-05-23 13:40:46  作者:guodian5261259  我要投稿
Linux初探欢迎您的投稿,投放方法请点击这里查看,我们会定期赠送精美小礼品给优秀的投稿作者。海纳百川 取则行远!LinuxGoo欢迎您的到来。
SQLserver2005 有一个ROW-NUMBER函数,他针对select返回的每一行,从1开始编号,赋予其连续的编号。因为在查询上应用了一个排序的标准后,只有通过编号才能够保证其顺......

SQLserver2005 有一个ROW-NUMBER函数,他针对select返回的每一行,从1开始编号,赋予其连续的编号。因为在查询上应用了一个排序的标准后,只有通过编号才能够保证其顺序是一致的。 select ROW-NUMBER()OVER(ORDER BY 列名)as Row,列名 from 表名

例:select row ,name from(select ROW-NUMBER()OVER(ORDER BY ProductId)as row,name from Product)as ProductWithRowNumbers where row>=6 and row<=10

下面是一个完整的存储过程例子:

CREATE PROCEDURE GetProductsOnDepartmentPromotion
(@DepartmentID INT,
@DescriptionLength INT,
@PageNumber INT,
@ProductsPerPage INT,
@HowManyProducts INT OUTPUT)
AS

-- declare a new TABLE variable
DECLARE @Products TABLE
(RowNumber INT,
ProductID INT,
Name VARCHAR(50),
Description VARCHAR(5000),
Price MONEY,
Image1FileName VARCHAR(50),
Image2FileName VARCHAR(50),
OnDepartmentPromotion BIT,
OnCatalogPromotion BIT)

-- populate the table variable with the complete list of products
INSERT INTO @Products
SELECT ROW_NUMBER() OVER (ORDER BY ProductID) AS Row,
ProductID, Name, SUBSTRING(Description, 1, @DescriptionLength) '...' AS Description,
Price, Image1FileName, Image2FileName, OnDepartmentPromotion, OnCatalogPromotion
FROM
(SELECT DISTINCT Product.ProductID, Product.Name,
SUBSTRING(Product.Description, 1, @DescriptionLength) '...' AS Description,
Price, Image1FileName, Image2FileName, OnDepartmentPromotion, OnCatalogPromotion
FROM Product INNER JOIN ProductCategory
ON Product.ProductID = ProductCategory.ProductID
INNER JOIN Category
ON ProductCategory.CategoryID = Category.CategoryID
WHERE Product.OnDepartmentPromotion = 1
AND Category.DepartmentID = @DepartmentID
) AS ProductOnDepPr

-- return the total number of products using an OUTPUT variable
SELECT @HowManyProducts = COUNT(ProductID) FROM @Products

-- extract the requested page of products
SELECT ProductID, Name, Description, Price, Image1FileName,
Image2FileName, OnDepartmentPromotion, OnCatalogPromotion
FROM @Products
WHERE RowNumber > (@PageNumber - 1) * @ProductsPerPage
AND RowNumber <= @PageNumber * @ProductsPerPage

前面介绍的方法不能在sqlsever2000中使用的,因为它不支持ROW-NUMBER函数。而是要使用一个IDENTITY列,来产生你所需要的排序。IDENTITY列也可以和表变量和临时表一起使用。淡然这个方法也可以再sqlsever2005中使用(事实上,在sqlserver2005中他运行的更好)。这个方法有个缺陷,因为sqlserver2000不能保证相同的顺序填充临时表,并且在两次连续的查询中,也无法保证每个行获得相同的行号。最坏的情况例如:同样的商品出现在不同的分页上。和通过使用临时表实现分页技术所取得的性能改进相比,这只是一个次要的缺点。

如果您需转载 在数据层实现分页技术,请注明来自LinuxGoo.com,其版权归原作者所有。请广大网友留言时遵纪守法,使用文明用语。如果您在应用中有什么问题,请在下面留言,我们会尽快解答。
来顶一下
近回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
相关文章
栏目热门