Monday, June 3, 2013

Updating a large table in batches

In order to update million of record using the UPDATE statement can be time-consuming and may lead to timeout errors and other issues. A better approach would be to commit the updates in batches and here is the PL/SQL recipe for doing it:

declare
   cursor c is select rowid id from <TABLE> order by rowid;
   counter NUMBER(10) := 0;
   rowids dbms_sql.urowid_table;  

begin
   dbms_output.enable;
   open c;
   loop  
      fetch c bulk collect into rowids limit 1000;
      forall i in 1..rowids.count
         update <TABLE> set date=SYSDATE
              where rowid = rowids(i);
      commit;
      counter := counter + 1;
      dbms_output.put_line('Updated batch ' || counter );
      exit when c%notfound;
   end loop;
   close c;
end;
/

The above PL/SQL would update the DATE column of the table <TABLE> in batches of 1000 and will be much faster than the traditional UPDATE statement.

No comments:

Search This Blog