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
  • 14,205
  • 26
  • 82
  • 117

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
  • 119,203
  • 23
  • 166
  • 186
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
  • 422,506
  • 82
  • 585
  • 676