Created
June 17, 2022 10:30
-
-
Save doeringp/59d7f692eadabb190f3137e24426a5ae to your computer and use it in GitHub Desktop.
Cursor-based pagination for SQL Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- The ID value of the last row from the previous page. | |
DECLARE @Cursor NVARCHAR(100) = '19'; | |
-- The number of rows you want for the next page. | |
DECLARE @PageSize INT = 10; | |
WITH [Query] AS ( | |
SELECT * FROM dbo.ProductModel | |
) | |
SELECT * FROM [Query] | |
ORDER BY Id ASC | |
OFFSET( | |
SELECT TOP 1 [RowNumber] | |
FROM( | |
SELECT | |
[Id] | |
,ROW_NUMBER() OVER (ORDER BY ID ASC) AS [RowNumber] | |
FROM [Query] | |
) [Temp] | |
WHERE [Temp].Id = @Cursor | |
) ROWS | |
FETCH NEXT @PageSize ROWS ONLY |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment