SQL SERVER中如何选择大量记录

2 sql-server records

我试图在具有数百万条记录的表中选择 SQL Server 中的 80,000 多条记录。问题是我有正确的索引,但返回记录集需要超过 15 分钟。

我正在使用 MS SQL Server 2000,我找到了一种使用存储过程的分页方法,但它使用了一个时态表,我必须插入整个结果集,然后选择我要在每页显示的记录数量。这个方法耗时太长。

对我可以实施的更快方法有什么帮助吗?

Cha*_*ana 5

您必须编辑它以实现用户过滤和排序选项的输入参数,但一般原则将适用.. 我在 2000/2001 时间范围内将这种技术与 SQL 2000 一起使用,并使用 90M 记录表为 150- 提供快速分页20 万行结果集。由于临时表中只有key,所以是一个非常窄、非常小的临时表,而且性能很快,(而且这一步只需要读取主表索引,而不是表本身)然后,当实际从主表生成数据以获取实际(较小)返回结果集(仅@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
Run Code Online (Sandbox Code Playgroud)