Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Efficient paging using SQL script

4.57/5 (4 votes)
28 Dec 2011CPOL 8.7K  
Hi, what about such solution?DECLARE @pageNumber INTDECLARE @rowsOnPage INTSET @rowsOnPage=5SET @pageNumber=2DECLARE @totalItemsToSelect INTSET @totalItemsToSelect=@rowsOnPage * @pageNumberSELECT TOP (@rowsOnPage) * FROM MainTrans WHERE ID IN( SELECT TOP...
Hi, what about such solution?

SQL
DECLARE @pageNumber INT
DECLARE @rowsOnPage INT

SET @rowsOnPage=5
SET @pageNumber=2

DECLARE @totalItemsToSelect INT
SET @totalItemsToSelect=@rowsOnPage * @pageNumber

SELECT TOP (@rowsOnPage) * FROM MainTrans WHERE ID IN
(
    SELECT TOP (@totalItemsToSelect) ID FROM MainTrans ORDER BY ID DESC
) ORDER BY ID ASC

it looks much shorter.

Thanks,
Kiryl

P.S. of course this solution works only if you have identity column. in my opinion identity column is a must for paging, moreover this approach works for any database not only for MS SQL

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)