Oracle SQL-如何使用分页循环记录?

时间:2019-01-10 12:32:47

标签: oracle stored-procedures plsql oracle-sqldeveloper

我正在使用一个Oracle数据库,其中有一个包含20条记录的表

CREATE TABLE MyTable (
    MY_RECORD_ID NUMBER PRIMARY KEY, 
    SOME_DATA_1 VARCHAR2(200), 
    SOME_DATA_2 VARCHAR2(200)
);

INSERT INTO MyTable VALUES (1, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (2, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (3, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (4, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (5, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (6, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (7, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (8, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (9, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (10, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (11, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (12, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (13, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (14, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (15, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (16, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (17, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (18, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (19, 'BLAH1', 'BLAH2');
INSERT INTO MyTable VALUES (20, 'BLAH1', 'BLAH2');

我想做的是遍历该表,并根据MY_RECORD_ID列一次选择5条记录。 OFFSETFETCH命令似乎允许我执行以下操作:

SELECT * 
FROM MyTable 
ORDER BY MY_RECORD_ID 
OFFSET 0 ROWS -- start at the first row
FETCH NEXT 5 ROWS ONLY;

我想将上面的语句插入循环中,以便可以对五行中的每一行执行数据操作(这样总共执行4次)。有没有办法使用存储过程来做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以对此类请求使用分析功能

SELECT my_record_id, some_data_1, some_data_2
  FROM (
        SELECT CEIL(ROW_NUMBER() OVER(ORDER BY mt.my_record_id) / 5/*set the page size*/) page_id
             ,mt.* 
          FROM MyTable mt
       ) t
 WHERE page_id = 1 /* set the desired page*/
ORDER BY my_record_id

您可以查看此文档

分析功能

https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm#SQLRF06174

问汤姆

https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1137577300346084930

其他示例

https://blogs.oracle.com/oraclemagazine/on-top-n-and-pagination-queries

答案 1 :(得分:1)

您可以通过使用批量收集来实现。

DECLARE
  TYPE t_MyTable_tab IS TABLE OF MyTable%ROWTYPE;
  l_tab    t_MyTable_tab ; 
  CURSOR c_data IS
    SELECT *
    FROM   MyTable;
BEGIN
  OPEN c_data;
  LOOP
    FETCH c_data
    BULK COLLECT INTO l_tab LIMIT 5; --- Here 5 is your limiting number

    -- Process contents of collection here.
    DBMS_OUTPUT.put_line(l_tab.count || ‘ rows’);
    EXIT WHEN c_data%NOTFOUND;
  END LOOP
  CLOSE c_data;
END;
/