我正在阅读有关如何有效地翻阅大型数据集的信息,因为我不满意Row_Number
并且Fetch
最糟糕。
这是文章: http ://www.4guysfromrolla.com/webtech/042606-1.shtml
现在这篇文章有这段代码:
CREATE PROCEDURE [dbo].[usp_PageResults_NAI]
(
@startRowIndex int,
@maximumRows int
)
AS
DECLARE @first_id int, @startRow int
-- A check can be added to make sure @startRowIndex isn't > count(1)
-- from employees before doing any actual work unless it is guaranteed
-- the caller won't do that
-- Get the first employeeID for our page of records
SET ROWCOUNT @startRowIndex
SELECT @first_id = employeeID FROM employees ORDER BY employeeid
-- Now, set the row count to MaximumRows and get
-- all records >= @first_id
SET ROWCOUNT @maximumRows
SELECT e.*, d.name as DepartmentName
FROM employees e
INNER JOIN Departments D ON
e.DepartmentID = d.DepartmentID
WHERE employeeid >= @first_id
ORDER BY e.EmployeeID
SET ROWCOUNT 0
GO
此演示代码看起来不错(与您看到的其他演示一样 :))。上面的代码之所以有效,只是因为他使用的是Order By employeeid
in SELECT @first_id = employeeID FROM employees ORDER BY employeeid
。
假设我有一个名为的字段FirstName
,并希望按此排序。那我怎么写上面的程序呢?上面的过程显然是行不通的,因为这样我们就不能写了,因为如果我们按名称订购WHERE employeeid >= @first_id
就不能得到。first_id
这是因为where
在之前执行order by
。
如果我们将上述查询更改为:
Select * From (SELECT e.*, d.name as DepartmentName
FROM employees e
INNER JOIN Departments D ON
e.DepartmentID = d.DepartmentID
ORDER BY e.EmployeeID) v WHERE employeeid >= @first_id
那么它会起作用,但这意味着,上面的查询会在更大的数据集上给出极差的性能。
那么,我们如何将上面的演示代码投入生产使用呢?任何帮助表示赞赏。