Equivalent of LIMIT and OFFSET for SQL Server?

前端 未结 16 1901
天命终不由人
天命终不由人 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:36

    In SQL server you would use TOP together with ROW_NUMBER()

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

    The closest I could make is

    select * FROM( SELECT *, ROW_NUMBER() over (ORDER BY ID ) as ct from [db].[dbo].[table] ) sub where ct > fromNumber  and ct <= toNumber
    

    Which I guess similar to select * from [db].[dbo].[table] LIMIT 0, 10

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

    This feature is now made easy in SQL Server 2012. This is working from SQL Server 2012 onwards.

    Limit with offset to select 11 to 20 rows in SQL Server:

    SELECT email FROM emailTable 
    WHERE user_id=3
    ORDER BY Id
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY;
    
    • ORDER BY: required
    • OFFSET: optional number of skipped rows
    • NEXT: required number of next rows

    Reference: https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql

    0 讨论(0)
  • 2020-11-22 06:40
    @nombre_row :nombre ligne par page  
    @page:numero de la page
    
    //--------------code sql---------------
    
    declare  @page int,@nombre_row int;
        set @page='2';
        set @nombre_row=5;
        SELECT  *
    FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY etudiant_ID ) AS RowNum, *
          FROM      etudiant
    
        ) AS RowConstrainedResult
    WHERE   RowNum >= ((@page-1)*@nombre_row)+1
        AND RowNum < ((@page)*@nombre_row)+1
    ORDER BY RowNum
    
    0 讨论(0)
  • 2020-11-22 06:42

    For me the use of OFFSET and FETCH together was slow, so I used a combination of TOP and OFFSET like this (which was faster):

    SELECT TOP 20 * FROM (SELECT columname1, columname2 FROM tablename
        WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS) aliasname
    

    Note: If you use TOP and OFFSET together in the same query like:

    SELECT TOP 20 columname1, columname2 FROM tablename
        WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS
    

    Then you get an error, so for use TOP and OFFSET together you need to separate it with a sub-query.

    And if you need to use SELECT DISTINCT then the query is like:

    SELECT TOP 20 FROM (SELECT DISTINCT columname1, columname2
        WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS) aliasname
    

    Note: The use of SELECT ROW_NUMBER with DISTINCT did not work for me.

    0 讨论(0)
  • 2020-11-22 06:42
    -- @RowsPerPage  can be a fixed number and @PageNumber number can be passed 
    DECLARE @RowsPerPage INT = 10, @PageNumber INT = 2
    
    SELECT *
    
    FROM MemberEmployeeData
    
    ORDER BY EmployeeNumber
    
    OFFSET @PageNumber*@RowsPerPage ROWS
    
    FETCH NEXT 10 ROWS ONLY
    
    0 讨论(0)
提交回复
热议问题