Row Offset in SQL Server

后端 未结 16 2649
醉酒成梦
醉酒成梦 2020-11-22 05:53

Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it\'s possible to do:

SELECT * FR         


        
16条回答
  •  佛祖请我去吃肉
    2020-11-22 06:16

    You should be careful when using the ROW_NUMBER() OVER (ORDER BY) statement as performance is quite poor. Same goes for using Common Table Expressions with ROW_NUMBER() that is even worse. I'm using the following snippet that has proven to be slightly faster than using a table variable with an identity to provide the page number.

    DECLARE @Offset INT = 120000
    DECLARE @Limit INT = 10
    
    DECLARE @ROWCOUNT INT = @Offset+@Limit
    SET ROWCOUNT @ROWCOUNT
    
    SELECT * FROM MyTable INTO #ResultSet
    WHERE MyTable.Type = 1
    
    SELECT * FROM
    (
        SELECT *, ROW_NUMBER() OVER(ORDER BY SortConst ASC) As RowNumber FROM
        (
            SELECT *, 1 As SortConst FROM #ResultSet
        ) AS ResultSet
    ) AS Page
    WHERE RowNumber BETWEEN @Offset AND @ROWCOUNT
    
    DROP TABLE #ResultSet
    

提交回复
热议问题