How to add pagination to the following SQL

时间秒杀一切 提交于 2019-12-25 18:25:35

问题


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



来源:https://stackoverflow.com/questions/11783023/how-to-add-pagination-to-the-following-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!