Skip to content

Instantly share code, notes, and snippets.

@doeringp
Created June 17, 2022 10:30
Show Gist options
  • Save doeringp/59d7f692eadabb190f3137e24426a5ae to your computer and use it in GitHub Desktop.
Save doeringp/59d7f692eadabb190f3137e24426a5ae to your computer and use it in GitHub Desktop.
Cursor-based pagination for SQL Server
-- 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