LIMIT 10..20 in SQL Server

后端 未结 15 2221
礼貌的吻别
礼貌的吻别 2020-11-22 11:21

I\'m trying to do something like :

SELECT * FROM table LIMIT 10,20

or

SELECT * FROM table LIMIT 10 OFFSET 10
相关标签:
15条回答
  • 2020-11-22 12:00

    How about this?

    SET ROWCOUNT 10 
    
    SELECT TOP 20 *
    FROM sys.databases
    ORDER BY database_id DESC
    

    It gives you the last 10 rows of the first 20 rows. One drawback is that the order is reversed, but, at least it's easy to remember.

    0 讨论(0)
  • 2020-11-22 12:02

    Unfortunately, the ROW_NUMBER() is the best you can do. It's actually more correct, because the results of a limit or top clause don't really have meaning without respect to some specific order. But it's still a pain to do.

    Update: Sql Server 2012 adds a limit -like feature via OFFSET and FETCH keywords. This is the ansi-standard approach, as opposed to LIMIT, which is a non-standard MySql extension.

    0 讨论(0)
  • 2020-11-22 12:03

    If you are using SQL Server 2012+ vote for Martin Smith's answer and use the OFFSET and FETCH NEXT extensions to ORDER BY,

    If you are unfortunate enough to be stuck with an earlier version, you could do something like this,

    WITH Rows AS
    (
        SELECT
                  ROW_NUMBER() OVER (ORDER BY [dbo].[SomeColumn]) [Row]
                , *
            FROM
                  [dbo].[SomeTable]
    )
    SELECT TOP 10
              *
         FROM
             Rows
        WHERE Row > 10
    

    I believe is functionaly equivalent to

    SELECT * FROM SomeTable LIMIT 10 OFFSET 10 ORDER BY SomeColumn
    

    and the best performing way I know of doing it in TSQL, before MS SQL 2012.


    If there are very many rows you may get better performance using a temp table instead of a CTE.

    0 讨论(0)
提交回复
热议问题