Created
August 16, 2022 16:04
-
-
Save JerryNixon/3523420dc2dfc112286903c23e933ed6 to your computer and use it in GitHub Desktop.
Paging SQL Results
This file contains hidden or 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
BEGIN TRANSACTION | |
CREATE TABLE x | |
( | |
Id INT NOT NULL PRIMARY KEY | |
, Name VARCHAR(150) NOT NULL | |
); | |
WITH generator (Id, Name) AS | |
( | |
SELECT 1, NEWID() | |
UNION ALL | |
SELECT ID + 1, NEWID() | |
FROM generator | |
WHERE ID < 20 | |
) | |
INSERT INTO x (Id, Name) | |
SELECT Id, Name | |
FROM generator | |
OPTION (MAXRECURSION 0); | |
DECLARE @pageSize INT = 5; | |
DECLARE @currentPage INT = 0; | |
DECLARE @pageCount INT = (SELECT COUNT(*) / @pageSize FROM x); | |
WHILE (@currentPage < @pageCount) | |
BEGIN | |
SELECT @currentPage + 1 AS Page, x.* | |
FROM x | |
ORDER BY x.Id | |
OFFSET @pageSize * @currentPage ROW | |
FETCH NEXT @pageSize ROWS ONLY | |
SET @currentPage = @currentPage + 1; | |
END | |
ROLLBACK TRANSACTION |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment