2

I want to select the rows between A and B from a table. The table has at least A rows but it might have less than B rows. For example if A = 2, B = 5 and the table has 3 rows it should return rows 2 and 3.

How could I get the rows in such a range?

I am using Microsoft SQL Server 2008.

user182945
  • 1,377
  • 3
  • 11
  • 14

2 Answers2

6

You can use something similar to what's being described in this SO question.

I.E.

SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY YOUR_ORDERED_FIELD) as row FROM YOUR_TABLE
 ) a WHERE row > 5 and row <= 10

Where A = 5 and B = 10 in your example.

Community
  • 1
  • 1
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
2
SELECT *,ROW_NUMBER() OVER 
    (ORDER BY ordercol) AS 'rank'
FROM table
where rank between @a and @b
Hogan
  • 69,564
  • 10
  • 76
  • 117