3

i know there is no limit x,y in sqlserver instead of it i use:

 select  ROW_NUMBER(),name OVER (ORDER BY name) AS
 myrow from pack  where myrow > 5 and myrow < 10

but it has following error:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'myrow'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'myrow'.

any idea?

Edit

i saw What is the Equivalent syntax of mysql " LIMIT " clause in SQL Server but it didn't solve my problem.

Community
  • 1
  • 1
Mahdi_Nine
  • 13,285
  • 26
  • 79
  • 116

2 Answers2

1

Try this one (for 2005 and higher) -

SELECT p.name
FROM ( 
    SELECT  
          name
        , myrow = ROW_NUMBER() OVER (ORDER BY name)  
    FROM dbo.pack
) p
WHERE myrow BETWEEN 5 AND 9

Or try this (for 2012) -

SELECT name
FROM dbo.pack
ORDER BY name 
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY
Devart
  • 115,199
  • 22
  • 161
  • 180
1

In SQL Server 2012 there it the OFFSET FETCH syntax

However, for older versions you have to use ROW_NUMBER but in a derived table

select
    name
from
    (
    select
       name,
       ROW_NUMBER() OVER (ORDER BY name) AS myrow
    from
       pack
    ) X
where
   myrow > 5 and myrow <= 10

Don't use 3 nested TOPs as per the suggested answer in the proposed duplicate

gbn
  • 408,740
  • 77
  • 567
  • 659