SQL Server Paging - The Holy Grail
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
DECLARE @startRow INT | |
SET @startrow = 50 | |
;WITH cols | |
AS | |
( | |
SELECT table_name, column_name, | |
ROW_NUMBER() OVER(ORDER BY table_name, column_name) AS seq, | |
ROW_NUMBER() OVER(ORDER BY table_name DESC, column_name desc) AS totrows | |
FROM [INFORMATION_SCHEMA].columns | |
) | |
SELECT table_name, column_name, totrows + seq -1 as TotRows | |
FROM cols | |
WHERE seq BETWEEN @startRow AND @startRow + 49 | |
ORDERBY seq |
Another version:
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
CREATE PROCEDURE LogRead | |
@PageNumber INT = 1, | |
@PageSize INT = 100 | |
AS | |
BEGIN | |
SET NOCOUNT ON; | |
-- Sanity check | |
IF (@PageNumber <= 0) | |
SET @PageNumber = 1; | |
WITH pg AS | |
( | |
SELECT Id | |
FROM Logs | |
ORDER BY Id DESC | |
OFFSET @PageSize * (@PageNumber - 1) ROWS | |
FETCH NEXT @PageSize ROWS ONLY | |
) | |
SELECT Added, LogLevel, LogText | |
FROM Logs L | |
INNER JOIN pg | |
ON pg.Id = L.Id | |
ORDER BY L.Id; | |
END; |