views:

46

answers:

2

I have a select statement, retrieve about 1000 record I want to modify it to return only some records defined by @startIndex and @count e.g. : If I said @startIndex=20 and @count=20 the result will be : from the 21th record to 40th
I try to make it, but it take the same time as if I retrieve the 1000 record

what is the best way to do that

+1  A: 

This is typically called Paging, there are lots of samples if you google for 'sql server paging', for example this MSDN blog post.

Alex K.
Thank You Alex, I have already tried to use the row_number ranking function. but unfortunately it duplicates the records if I used it with Distinct
+1  A: 
WITH data AS (SELECT DISTINCT name FROM sysobjects),
     ranked AS (SELECT ROW_NUMBER() OVER (ORDER BY name) rownum, * FROM data)
SELECT * FROM ranked 
WHERE rownum BETWEEN @startIndex + 1 AND @startIndex + @count 
ORDER BY rownum
Anthony Faull
Thank You Anthony, But what if the ID not unique and I want to retrieve Distinct IDs only, Row_Numbers duplicate data
e.g. all data without row_number = 100, after using it and using distinct it become about 140 or 150 repeat some records and I don't know how
You can remove the distinct and GROUP BY id instead.
Alex K.
I've update my answer to get distinct rows.
Anthony Faull