1

I am new to SQL Server 2008, and I need some help in query for pagination logic on my JSF page.

Here is my query:

select * 
from ShipmentHistory sh 
where sh.CCIPortID in ? 
order by sh.TrackingNumber, sh.CreateTimeStamp

for the first time I need to get only 100 records from db and when ever the user clicks on next on my JSF page I need to fetch next 100 records only. Am keep tracking of user clicks on the page i.e next and previous button.

Thanks for your time.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
userJ
  • 65
  • 1
  • 11
  • Search for "SQL Server pagination", and you'll find [many](http://stackoverflow.com/questions/109232/what-is-the-best-way-to-paginate-results-in-sql-server) [answers](http://www.codeproject.com/Articles/12338/Using-ROW_NUMBER-to-paginate-your-data-with-SQL-Se) – Andomar Mar 20 '12 at 15:51

1 Answers1

3

First, you'll need to perform a count of your result set, so you know how many total records you have, and how many pages will be displaying the data.

Next, you'll need to specify the start and end rows that you want to retrieve, and then use a query similar to the following to pull that chunk of your results.

SELECT * FROM (
    SELECT
        *,
        ROW_NUMBER() OVER (ORDER BY sh.TrackingNumber, sh.CreateTimeStamp) AS rn,
    FROM ShipmentHistory sh 
    WHERE sh.CCIPortID in ? 
) AS ordered
WHERE rn >= @startRow AND rn < @endRow

Note: Don't use SELECT *, replace this with the actual columns that you need to return.

Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109