我试图在 SQL Server 中具有数百万条记录的表中选择超过 80,000 条记录。问题是我有正确的索引,但返回记录集需要超过 15 分钟。
我正在使用 MS SQL Server 2000,我找到了一种使用存储过程的分页方法,但它使用了一个时态表,我必须插入整个结果集,然后选择我要在每页显示的记录数量。此方法耗时太长。
有什么帮助可以帮助我更快地实现吗?
最佳答案
您必须编辑此内容以实现用户过滤和排序选项的输入参数,但一般原则将适用。我在 2000/2001 时间范围内使用 SQL 2000 技术和 90M 记录表来提供快速分页对于 150-200k 行结果集。由于临时表中只有键,因此它是一个非常窄、非常小的临时表,并且性能很快,(并且对于这一步,它只需要读取主表索引,而不是表本身)然后,当实际从主表生成实际(较小)返回结果集的数据(仅@PageSize行)时,查询只需读取很少的记录...
Create Procedure GetPagedData
@Page Integer = 1,
@PageSize Integer = 100,
@UsersFilteringCOnditions,
@UsersSortOptions
As
Set NoCount On
Declare @Start Integer,
Declare @End Integer
Declare @NumRecs Integer
-- Declare a temp table variable to hold all the pk values...
Declare @Keys Table (rowNum integer Identity Primary Key NotNull,
keyVal Integer Not Null)
-- Insert all the Primary Keys into the temp table variable...
Insert @keys(keyVal)
Select PrimaryKey From MyMillionRowTable
Where UsersFilterConditionsAreTrue
Order By UsersSortOptions
-- Then, select from your big table only the data
-- from the rows for the page the user wants
Select @NumRecs = Count(*) From Keys
Set @End = @Page * @PageSize
Set @Start = @End + 1 - @PageSize
Select {Insert ColumnListHere}
From MyMillionRowTable T
Join @Keys K On K.KeyVal = T.PrimaryKey
Where K.rowNum Between @Start And @End
关于sql-server - 如何在SQL SERVER中选择大量记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/381145/