how to select first N rows from a table in T-SQL?

前端 未结 7 903
耶瑟儿~
耶瑟儿~ 2020-12-10 10:54

Is there any way to select, for example, first 10 rows of a table in T-SQL (working MSSQL)?
I think I saw something in Oracle defined as rownum meta variable, used in a

7条回答
  •  感动是毒
    2020-12-10 11:30

    You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.

    SELECT * 
    FROM (SELECT row_number() over (order by UserID) AS line_no, * 
          FROM dbo.User) as users
    WHERE users.line_no < 10
    OR users.line_no BETWEEN 34 and 67
    

    You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.

    Msg 4108, Level 15, State 1, Line 3
    Windowed functions can only appear in the SELECT or ORDER BY clauses.
    

提交回复
热议问题