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

后端 未结 30 3030
执笔经年
执笔经年 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:36

    Here's a generic version of a sproc I recently wrote for Oracle that allows for dynamic paging/sorting - HTH

    -- p_LowerBound = first row # in the returned set; if second page of 10 rows,
    --                this would be 11 (-1 for unbounded/not set)
    -- p_UpperBound = last row # in the returned set; if second page of 10 rows,
    --                this would be 20 (-1 for unbounded/not set)
    
    OPEN o_Cursor FOR
    SELECT * FROM (
    SELECT
        Column1,
        Column2
        rownum AS rn
    FROM
    (
        SELECT
            tbl.Column1,
            tbl.column2
        FROM MyTable tbl
        WHERE
            tbl.Column1 = p_PKParam OR
            tbl.Column1 = -1
        ORDER BY
            DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 1, Column1, 'X'),'X'),
            DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 1, Column1, 'X'),'X') DESC,
            DECODE(p_sortOrder, 'A', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate),
            DECODE(p_sortOrder, 'D', DECODE(p_sortColumn, 2, Column2, sysdate),sysdate) DESC
    ))
    WHERE
        (rn >= p_lowerBound OR p_lowerBound = -1) AND
        (rn <= p_upperBound OR p_upperBound = -1);
    

提交回复
热议问题