How to select the nth row in a SQL database table?

后端 未结 30 2961
执笔经年
执笔经年 2020-11-22 06:06

I\'m interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can b

30条回答
  •  借酒劲吻你
    2020-11-22 06:32

    When we used to work in MSSQL 2000, we did what we called the "triple-flip":

    EDITED

    DECLARE @InnerPageSize int
    DECLARE @OuterPageSize int
    DECLARE @Count int
    
    SELECT @Count = COUNT() FROM 
    SET @InnerPageSize = @PageNum * @PageSize
    SET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize)
    
    IF (@OuterPageSize < 0)
        SET @OuterPageSize = 0
    ELSE IF (@OuterPageSize > @PageSize)
        SET @OuterPageSize = @PageSize
    
    DECLARE @sql NVARCHAR(8000)
    
    SET @sql = 'SELECT * FROM
    (
        SELECT TOP ' + CAST(@OuterPageSize AS nvarchar(5)) + ' * FROM
        (
            SELECT TOP ' + CAST(@InnerPageSize AS nvarchar(5)) + ' * FROM 
    ORDER BY ASC ) AS t1 ORDER BY DESC ) AS t2 ORDER BY ASC' PRINT @sql EXECUTE sp_executesql @sql

    It wasn't elegant, and it wasn't fast, but it worked.

    提交回复
    热议问题