Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Efficient paging using SQL script

, 28 Dec 2011
Rate this:
Please Sign up or sign in to vote.
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?
 
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)

About the Author

NeoPunk

Belarus Belarus
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 4 I think this script works well, but ... PinmemberRobby Tendean28-Dec-11 16:12 
GeneralReason for my vote of 3 The alternative is pretty solid if y... PinmemberHelluin28-Dec-11 6:01 
Reason for my vote of 3
The alternative is pretty solid if you do not remove any records from the containing table.
Thing I learned during working with databases and interfaces though is that the identity column stops identifying the data in a scenario where records are actualy getting removed from tables. (not only marked as 'deleted')
In that case ID columns are useless for paging.
 
EDIT: Dang, did not read through the permalink. As Pablo said, of course.
GeneralActually: 1. TOP does not work on Oracle (at least versions ... PinmemberPablo Aliskevicius28-Dec-11 4:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 28 Dec 2011
Article Copyright 2011 by NeoPunk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid