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不能保证相同的顺序填充临时表,并且在两次连续的查询中,也无法保证每个行获得相同的行号。最坏的情况例如:同样的商品出现在不同的分页上。和通过使用临时表实现分页技术所取得的性能改进相比,这只是一个次要的缺点。
1/2 1 2 下一页 尾页 |