Equivalent of LIMIT and OFFSET for SQL Server?

前端 未结 16 2259
天命终不由人
天命终不由人 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.

提交回复
热议问题