快捷搜索:

SQL Server 2005: 利用新的ranking函数实现高效的数据

近来MSDN Magazine上的一篇文章10 Tips for Writing High-Performance Web Applications提到了有效的数据分页技巧对前进ASP .NET法度榜样机能的紧张性;并给出了一个实现数据分页的stored procedure的例子,抄写如下:

CREATE PROCEDURE northwind_OrdersPaged

(

@PageIndex int,

@PageSize int

)

AS

BEGIN

DECLARE @PageLowerBound int

DECLARE @PageUpperBound int

DECLARE @RowsToReturn int

-- First set the rowcount

SET @RowsToReturn = @PageSize * (@PageIndex1)

SET ROWCOUNT @RowsToReturn

-- Set the page bounds

SET @PageLowerBound = @PageSize * @PageIndex

SET @PageUpperBound = @PageLowerBound@PageSize1

-- Create a temp table to store the select results

CREATE TABLE #PageIndex

(

IndexId int IDENTITY (1, 1) NOT NULL,

OrderID int

)

-- Insert into the temp table

INSERT INTO #PageIndex (OrderID)

SELECT

OrderID

FROM

Orders

ORDER BY

OrderID DESC

-- Return total count

SELECT COUNT(OrderID) FROM Orders

-- Return paged results

SELECT

O.*

FROM

Orders O,

#PageIndex PageIndex

WHERE

O.OrderID = PageIndex.OrderID AND

PageIndex.IndexID > @PageLowerBound AND

PageIndex.IndexID

在SQL Server 2000里面,因为系统供给了内建的ranking函数,为了给Orders表天生行号,我们不再必要使用Identity字段。

例如,使用SQL Server 2000的ROW_NUMBER()函数,按orderID字段逆序排列,给Orders表天生行号的语句如下:

SELECT ROW_NUMBER() OVER(ORDER BY ordered DESC) AS rownum, ordered

FROM Orders

ORDER BY rownum DESC

基于这些新的ranking函数,您可以跟方便的实现数据的分页操作。

关于SQL Server 2005的T-SQL新特点,见文档:

http://msdn.microsoft.com/sql/archive/default.aspx?pull=/library/en-us/dnsql90/html/sql_05tsqlenhance.asp

您可能还会对下面的文章感兴趣: