1

I have the following SQL statement:

SELECT [id], [name]
FROM [dbo.test_db_002] t1
LEFT JOIN [dbo.test_db_003] t2 ON t1.[id] = t2.[itmid]
ORDER BY t2.[iid] ASC;

This seems very simple, but I can't figure it out. I need to add LIMIT N,M to it to retrieve M items from the N'th one, but I keep getting errors around 'limit' word. I tried putting that LIMIT clause everywhere I could inside the sql statement above with no avail.

PS. I'm writing for SQL Server that comes with VS2010.

Adam Wenger
  • 17,100
  • 6
  • 52
  • 63
ahmd0
  • 16,633
  • 33
  • 137
  • 233

4 Answers4

4

To answer for your query, you may want: (depending on your values for M and N)

WITH cte AS
(
   SELECT [id], [name], ROW_NUMBER() OVER (ORDER BY t2.[iid] ASC) AS rowNumber
   FROM [dbo.test_db_002] t1
   LEFT JOIN [dbo.test_db_003] t2 ON t1.[id] = t2.[itmid]
)
SELECT [id], [name]
FROM cte
WHERE rowNumber BETWEEN 3 AND 5

Something to watch out for, the values in the between are BETWEEN N AND N + M

Also, here's a link with information about Common Table Expressions which is the WITH cte syntax I used.

Adam Wenger
  • 17,100
  • 6
  • 52
  • 63
  • Jesus Christ! No wonder I have no hair left after trying to come up with this myself )) Let me try it out... – ahmd0 Nov 11 '11 at 01:24
3

There's no direct equivalent to LIMIT N,M in SQL Server, but you can do something like this:

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

See here for some more info: "LIMIT" in SQL Server

Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
  • Thanks, but how can I use all that "monstrosity" in my query? (Sorry, for calling your code that -- I'm actually referring to SQL Server....) – ahmd0 Nov 11 '11 at 01:22
1

You could use Row_Number()

example:

select * from 
(
  select cola, colb, row_number() over (order by col1 desc) as row
  from table ) x
where row between value1 and value2
Icarus
  • 63,293
  • 14
  • 100
  • 115
  • 1
    While "use `ROW_NUMBER`" is the correct answer, your example won't work on SQL Server. You need to use a sub-query or CTE, as shown in the other answers. – LukeH Nov 11 '11 at 01:17
0

Limit with offset in sql server 2012:

SELECT email FROM myTable
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;

//offset - no. of skipped rows

//next - required no. of next rows

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226