How to add pagination to the following SQL

2019-08-17 14:44发布

问题:

I've got the following SQL and I want to know how to page it:

I've got variables for @skip and @top so I can page through..

SELECT ID FROM (
  SELECT COUNT(*) AS ID, -1 AS [Weight]
  FROM Employees i
    INNER JOIN #WeightedIDs w
    ON (i.ID = w.ID)
  WHERE (i.DepartmentID = 10 and i.ShiftID = 2)

  UNION ALL

  SELECT i.ID, w.[Weight]
  FROM Employees i
    INNER JOIN #WeightedIDs w
    ON (i.ID = w.ID)
  WHERE (i.DepartmentID = 10 and i.ShiftID = 2)
) x
ORDER BY x.[Weight] ASC

UPDATE:

I've got the following but it doesn't work at all:

DECLARE @skip INT, @top INT
SET @skip = 30
SET @top = 100

;WITH PaginatedResults AS
(
  SELECT ID, w.[Weight],
    ROW_NUMBER() OVER (ORDER BY w.[Weight] ASC) AS RowNum
  FROM Employees i 
    INNER JOIN #WeightedIDs w 
    ON (i.ID = w.ID)  
  WHERE (i.DepartmentID = 10 and i.ShiftID = 2)
)
SELECT ID FROM (
  SELECT COUNT(*) AS ID, -1 AS [Weight]
  FROM Employees i 
    INNER JOIN #WeightedIDs w 
    ON (i.IssueID = w.id)  
  WHERE FlightID > 2 and IssueID > 0

  UNION ALL

  SELECT ID, [Weight]
  FROM PaginatedResults
  WHERE RowNum >= @skip AND RowNum < @skip + @top
) x
ORDER BY x.[Weight] ASC

回答1:

This link shows a nice pagination mechanism for 2008:

Equivalent of LIMIT and OFFSET for SQL Server?

In SQL 2012 there are OFFSET and FETCH keywords that make it very easy to paginate.

This question should be applicable as well:

How to do pagination in SQL Server 2008