Equivalent of LIMIT and OFFSET for SQL Server?

前端 未结 16 1902
天命终不由人
天命终不由人 2020-11-22 06:07

In PostgreSQL there is the Limit and Offset keywords which will allow very easy pagination of result sets.

What is the equivalent syntax f

相关标签:
16条回答
  • 2020-11-22 06:52

    Specifically for SQL-SERVER you can achieve that in many different ways.For given real example we took Customer table here.

    Example 1: With "SET ROWCOUNT"

    SET ROWCOUNT 10
    SELECT CustomerID, CompanyName from Customers
    ORDER BY CompanyName
    

    To return all rows, set ROWCOUNT to 0

    SET ROWCOUNT 0  
    SELECT CustomerID, CompanyName from Customers
        ORDER BY CompanyName
    

    Example 2: With "ROW_NUMBER and OVER"

    With Cust AS
    ( SELECT CustomerID, CompanyName,
    ROW_NUMBER() OVER (order by CompanyName) as RowNumber 
    FROM Customers )
    select *
    from Cust
    Where RowNumber Between 0 and 10
    

    Example 3 : With "OFFSET and FETCH", But with this "ORDER BY" is mandatory

    SELECT CustomerID, CompanyName FROM Customers
    ORDER BY CompanyName
    OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY
    

    Hope this helps you.

    0 讨论(0)
  • 2020-11-22 06:53

    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
    

    The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).

    Note: the @Offset parameter should use one-based indexing for this rather than the normal zero-based indexing.

    0 讨论(0)
  • 2020-11-22 06:53

    There is here someone telling about this feature in sql 2011, its sad they choose a little different keyword "OFFSET / FETCH" but its not standart then ok.

    0 讨论(0)
  • 2020-11-22 06:55

    You can use ROW_NUMBER in a Common Table Expression to achieve this.

    ;WITH My_CTE AS
    (
         SELECT
              col1,
              col2,
              ROW_NUMBER() OVER(ORDER BY col1) AS row_number
         FROM
              My_Table
         WHERE
              <<<whatever>>>
    )
    SELECT
         col1,
         col2
    FROM
         My_CTE
    WHERE
         row_number BETWEEN @start_row AND @end_row
    
    0 讨论(0)
提交回复
热议问题