【问题标题】:What is the most efficient way to page large amounts of data in SQL Server 2000?在 SQL Server 2000 中对大量数据进行分页的最有效方法是什么?
【发布时间】:2011-06-04 22:18:08
【问题描述】:
如果我有一个包含大量信息的查询(比如几个视图,每个视图都访问少数几个表,许多表有数万行),我只需要从中获取 10 条记录向用户显示,在性能方面,在仍然支持 SQL Server 2000 的同时检索这些记录的最佳方式是什么?一旦我可以使用 SQL Server 2005,ROW_NUMBER 似乎是显而易见的选择(如果我错了请纠正我),但是在 2000 年该怎么办?
【问题讨论】:
标签:
sql-server
performance
sql-server-2000
paging
【解决方案1】:
Greg Hamilton has an article 在变量中使用SET ROWCOUNT 和SELECTing 以避免引用不需要的行,从而获得了一些非常引人注目的性能结果。但是,MSDN says
如果在选择列表中引用了变量,则应为其分配一个标量值,否则 SELECT 语句应仅返回一行。
然后它继续说
请注意,只有在分配之间存在引用时才能看到效果。
如果 SELECT 语句返回多行且变量引用非标量表达式,则该变量设置为结果集中最后一行中表达式返回的值。
表示在这种情况下真的没问题(对吗?)
Greg 的结局是这样的:
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
此方法假定您有一个唯一的 ID 进行排序,我认为您不能在对非唯一的 DateTime 列进行排序时按原样使用此方法。