LIMIT 10..20 in SQL Server

后端 未结 15 2218
礼貌的吻别
礼貌的吻别 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 11:40

    So far this format is what is working for me (not the best performance though):

    SELECT TOP {desired amount of rows} * 
    FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY {order columns} asc)__row__ FROM {table})tmp
    WHERE __row__ > {offset row count}
    

    A note on the side, paginating over dynamic data can lead to strange/unexpected results.

    0 讨论(0)
  • 2020-11-22 11:41

    A good way is to create a procedure:

    create proc pagination (@startfrom int ,@endto int) as
    SELECT * FROM ( 
      SELECT *, ROW_NUMBER() OVER (ORDER BY name desc) as row FROM sys.databases 
     ) a WHERE a.row > @startfrom and a.row <= @endto
    

    just like limit 0,2 /////////////// execute pagination 0,4

    0 讨论(0)
  • 2020-11-22 11:42
    select * from (select id,name,ROW_NUMBER() OVER (ORDER BY id  asc) as row
    from tableName1) tbl1
    where tbl1.row>=10 and tbl1.row<=15
    

    Will print rows from 10 to 15.

    0 讨论(0)
  • 2020-11-22 11:44

    as you found, this is the preferred sql server method:

    SELECT * FROM ( 
      SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases 
     ) a WHERE a.row > 5 and a.row <= 10
    
    0 讨论(0)
  • 2020-11-22 11:47

    The equivalent of LIMIT is SET ROWCOUNT, but if you want generic pagination it's better to write a query like this:

    ;WITH Results_CTE AS
    (
        SELECT
            Col1, Col2, ...,
            ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
        FROM Table
        WHERE <whatever>
    )
    SELECT *
    FROM Results_CTE
    WHERE RowNum >= @Offset
    AND RowNum < @Offset + @Limit
    
    0 讨论(0)
  • 2020-11-22 11:48

    From the MS SQL Server online documentation (http://technet.microsoft.com/en-us/library/ms186734.aspx ), here is their example that I have tested and works, for retrieving a specific set of rows. ROW_NUMBER requires an OVER, but you can order by whatever you like:

    WITH OrderedOrders AS
    (
      SELECT SalesOrderID, OrderDate,
      ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
      FROM Sales.SalesOrderHeader 
    ) 
    SELECT SalesOrderID, OrderDate, RowNumber  
    FROM OrderedOrders 
    WHERE RowNumber BETWEEN 50 AND 60;
    
    0 讨论(0)
提交回复
热议问题