question

fashraf avatar image
fashraf asked

1 million rows to be displayed in sets of 100

I have almost 1 mill roes and he size keeps growing. In order not to delay the query I need to display Top 100 followed by 101-200 followed by 201 -300 etc.I am not loading all the data at one time .I need the 100 rows first and then on button click retrieve the next 100 and so on .I have to dispay the data in a single view so paging is not allowed in the grid.Thank you !
sql-server-2008datapaging
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
Just a comment... While the business requirement may be to return all 1 million rows, processing millions of rows, even using some of the efficient operations suggested below, is a bad design. You need to push back on the business requirement and get them to define some mechanisms of filtering the data first. Trust me, no one ever reads millions of rows. They just want to know that the data is there. You should never try to return it to them all at once.
1 Like 1 ·
Håkan Winther avatar image
Håkan Winther answered
In SQL 2008, you can use a cte and rownumber to get the records in batches of x records. See the sample below: DECLARE @start INT = 1 DECLARE @batchSize INT = 100 ;WITH ctePage AS ( SELECT ROW_NUMBER() OVER(ORDER BY cp.id ) AS recordno, * FROM dwh.counterpart cp WHERE cp.reportDate = '2012-05-20' ) SELECT * FROM ctePage WHERE [ctePage].[recordno] BETWEEN @start AND @start + @batchSize In SQL 2012, you can use OFFSET in the order by clause, without the need for the CTE and rownumber.
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

ThomasRushton avatar image
ThomasRushton answered
In addition to @Håkan Winther's answer, you might want to have a read of [Dave Ballantyne's blog][1] on the subject. [1]: http://sqlblogcasts.com/blogs/sqlandthelike/archive/2012/04/26/offset-without-offset.aspx
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.