SQL query How to get a specific number of records

I have a select statement retrieving about 1000 records I want to modify it to only return some records defined by @startIndex and @count for example: If I said @startIndex = 20 and @count = 20 the result would be: from the 21st record to 40th
I am trying to do this, but it takes the same time as if I got 1000 records

What is the best way to do this

+2


a source to share


2 answers


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

      



+1


a source


This is usually called paging, there are many examples if you are using google to swap sql server like this MSDN blog post .



+1


a source







All Articles