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

Efficient paging using SQL script

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
10 Jan 2012CPOL 7.9K   2   2
string Query = string.Format(@"SELECT * FROM (SELECT *, " + @"ROW_NUMBER() OVER(ORDER BY PRODUCT_ID DESC ) AS ROW_NUM FROM({0}) " + @"AS TEMP_INNER) AS TEMP_OUTER WHERE ROW_NUM BETWEEN '{1}' AND " + @"({2} + {3}) - 1", strSql, startRowIndex, startRowIndex, maximumRows);
C#
string Query = string.Format(@"SELECT * FROM (SELECT *, " + 
     @"ROW_NUMBER() OVER(ORDER BY PRODUCT_ID DESC ) AS ROW_NUM  FROM({0}) " + 
     @"AS TEMP_INNER) AS TEMP_OUTER  WHERE ROW_NUM BETWEEN '{1}' AND " + 
     @"({2} + {3}) - 1", strSql, startRowIndex, startRowIndex, maximumRows);

License

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


Written By
Software Developer PowerObjects
Pakistan Pakistan
I am a professional Software Developer. I have experience in developing Windows Applications, e-commerce Portals, Content Management Systems and Data driven websites.
My technical forte includes: C#, ASP.NET, ADO.NET, JavaScript, jQuery, SQL Server, Design Patterns.
My interests involves programming, website development, developing applications for Android and learning subjects related to Software Engineering/Information Systems. Currently I am working as a Software Engineer at PowerObjects Pvt Ltd.

Comments and Discussions

 
GeneralI think that it comes down to the proper separation of the l... Pin
Riverama26-Jan-12 12:39
professionalRiverama26-Jan-12 12:39 
I think that it comes down to the proper separation of the layers in your business model; first you Should define that query in a store procedure, and as initially stated here, use parameters to pass your filtering data.

You are tempted to do the calculation with your paging parameters beforehand, but that creates dependency between your db and the DAL. If you ever need to change your paging logic, you'll have to do it in both layers since one depends in the calculations of the other, alternatively if you left the calculation to the procedure, your DAL would not care how it's done and its only job is to pass the parameters and expect a response.

It's like asking a carpenter to make you a table and explaining him how to drive the nails.
GeneralIgnoring the issues with not using SQL parameters, why not j... Pin
Andrew Rissing10-Jan-12 4:06
Andrew Rissing10-Jan-12 4:06 

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.