How do I use bulk collect and insert in Pl/SQl

前端 未结 3 1554
难免孤独
难免孤独 2020-12-19 19:09

I want to fetch around 6 millions rows from one table and insert them all into another table. How do I do it using BULK COLLECT and FORALL ?

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 20:06

    declare
      -- define array type of the new table
      TYPE new_table_array_type IS TABLE OF NEW_TABLE%ROWTYPE INDEX BY BINARY_INTEGER;
    
      -- define array object of new table
      new_table_array_object new_table_array_type;
    
      -- fetch size on  bulk operation, scale the value to tweak
      -- performance optimization over IO and memory usage
      fetch_size NUMBER := 5000;
    
      -- define select statment of old table
      -- select desiered columns of OLD_TABLE to be filled in NEW_TABLE
      CURSOR old_table_cursor IS
        select * from OLD_TABLE; 
    
    BEGIN
    
      OPEN old_table_cursor;
      loop
        -- bulk fetch(read) operation
        FETCH old_table_cursor BULK COLLECT
          INTO new_table_array_object LIMIT fetch_size;
        EXIT WHEN old_table_cursor%NOTFOUND;
    
        -- do your business logic here (if any)
        -- FOR i IN 1 .. new_table_array_object.COUNT  LOOP
        --   new_table_array_object(i).some_column := 'HELLO PLSQL';    
        -- END LOOP;    
    
        -- bulk Insert operation
        FORALL i IN INDICES OF new_table_array_object SAVE EXCEPTIONS
          INSERT INTO NEW_TABLE VALUES new_table_array_object(i);
        COMMIT;
    
      END LOOP;
      CLOSE old_table_cursor;
    End;
    

    Hope this helps.

提交回复
热议问题