Click here to Skip to main content
15,887,027 members
Articles / Database Development / SQL Server
Alternative
Tip/Trick

Efficient paging using SQL script

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
10 Jan 2012CPOL 11.2K   5   6
Take a look at this:DECLARE @ActualRow = 1; /*Start in first item*/DECLARE @ItensCount = 100; /*100 itens for page*/DECLARE @Page = 1; /*Start in first page*/SELECT * FROM(SELECT *, ROWNUMBER() OVER(ORDER BY Name) as ROWNUM FROM Users) as UsWHERE ROWNUM BETWEEN...

Take a look at this:


SQL
DECLARE @ActualRow = 1;      /*Start in first item*/
DECLARE @ItensCount = 100;   /*100 itens for page*/
DECLARE @Page = 1;           /*Start in first page*/

SELECT * FROM
(SELECT *, ROWNUMBER() OVER(ORDER BY Name) as ROWNUM FROM Users) as Us
WHERE ROWNUM BETWEEN @ActualRow AND (@ActualRow + @ItensCount / @page) -1

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Well, i never use view/function to do paging before. Maybe y... Pin
Robby Tendean10-Jan-12 14:27
Robby Tendean10-Jan-12 14:27 
GeneralReason for my vote of 5 very cleaver, much more efficient Pin
Herman<T>.Instance10-Jan-12 10:33
Herman<T>.Instance10-Jan-12 10:33 
GeneralReason for my vote of 4: I prefer not to do any calculation ... Pin
Robby Tendean28-Dec-11 16:09
Robby Tendean28-Dec-11 16:09 
GeneralRe: if you would use this in a niew or function iw would not wor... Pin
Herman<T>.Instance10-Jan-12 10:33
Herman<T>.Instance10-Jan-12 10:33 
GeneralReason for my vote of 4 The reason i put 4 stars is because ... Pin
Robby Tendean28-Dec-11 16:00
Robby Tendean28-Dec-11 16:00 
GeneralReason for my vote of 5 That is almost the way I do it. (sel... Pin
Helluin28-Dec-11 6:03
Helluin28-Dec-11 6:03 

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

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