如何使用SQL Server查询中的分页循环?

时间:2018-02-22 17:23:20

标签: sql-server sql-server-2014

我有一个SQL查询,它返回大约350,000条记录(这可能因标准而异)。我正在添加paging以获得更好的效果。我想要的是,首先加载1000条记录并继续运行至350,000条。

我如何实现这一目标?

  • 获取查询计数并添加循环?如果是,如何设置@Iterator值?
  • 我是否需要使用;WITH AS ()

我将@PageSize计数设置为我想要的记录总数(这是正确的吗?)。在这里,我得到20412条记录。如果我将@PageSize设置为1000,则不确定如何获取下一个1000条记录,依此类推。

查询:

-- USING GENERAL PAGING

DECLARE @ConceptId INT, @PageNumber INT, @PageSize INT, @Iterator INT
SET @ConceptId = 2076
SET @PageNumber = 1
SET @PageSize = 
(
    SELECT COUNT(*)
    FROM ScheduledBulkUpdate(NOLOCK) SBU
    INNER JOIN ScheduledBulkUpdateRecurring(NOLOCK) SBR ON SBR.BatchId = SBU.BatchId
    WHERE SBU.ConceptId = @ConceptId
)
SET @Iterator = 0

PRINT @PageSize

--WHILE (@Iterator < @PageSize)
    --BEGIN

       SELECT DISTINCT SBU.BatchId AS Status,
            CAST(SBR.ExecutionTime AS DATE) AS StartRunDate,
            CAST(SBR.ExecutionTime AS TIME) AS StartRunTime,
            CAST(SBR.ExecutionTime AS DATE) AS EndRunDate,
            CAST(SBR.ExecutionTime AS TIME) AS EndRunTime,
            SBU.ScheduleID AS JobId,
            SBU.Name AS JobName,
             (
                SELECT concept
                FROM Concept
                WHERE conceptid = SBU.ConceptId
             ) AS ConceptName,
            SBU.ConceptId AS ConceptId,
            CAST(SBU.ScheduledStartDateTime AS  DATE) AS StartDate,
            CAST(SBU.ScheduledEndDateTime AS  DATE) AS EndDate,
            SBU.Frequency  AS Frequency,
            SBU.Query AS Query,
            SBU.Submitter AS Submitter
       FROM ScheduledBulkUpdate(NOLOCK) SBU
           INNER JOIN ScheduledBulkUpdateRecurring(NOLOCK) SBR ON SBR.BatchId = SBU.BatchId
       WHERE SBU.ConceptId = @ConceptId
       ORDER BY SBU.BatchId
       OFFSET @PageSize * (@PageNumber - 1) ROWS 
       FETCH NEXT @PageSize ROWS ONLY

       --Set @Iterator = @Iterator + 1
    --END

0 个答案:

没有答案