在oracle中使用commit进行批量更新

时间:2017-03-09 14:24:37

标签: sql oracle plsql

我正在为100万条记录的记录执行批量更新操作。我需要在每5000条记录之间进行COMMIT,我该如何执行?

update tab1 t1
   set (col1,col2,col3,col4)= 
   (select col1,col2,col3,col4 from tab_m where row_id= t1.row_id);

2 个答案:

答案 0 :(得分:0)

如果您要在PLSQL中寻找解决方案,可以使用BULK INSERT/UPDATE进行,如下所示:

  DECLARE
       c_limit PLS_INTEGER := 100;

       CURSOR employees_cur
       IS
          SELECT employee_id
            FROM employees
           WHERE department_id = department_id_in;

       TYPE employee_ids_t IS TABLE OF  employees.employee_id%TYPE;

       l_employee_ids   employee_ids_t;
    BEGIN
       OPEN employees_cur;

       LOOP
          FETCH employees_cur
          BULK COLLECT INTO l_employee_ids
          LIMIT c_limit;      -- This will make sure that every iteration has 100 records selected

          EXIT WHEN l_employee_ids.COUNT = 0;           

        FORALL indx IN 1 .. l_employee_ids.COUNT SAVE EXCEPTIONS
          UPDATE employees emp  -- Updating 100 records at 1 go.
             SET emp.salary =
                    emp.salary + emp.salary * increase_pct_in
           WHERE emp.employee_id = l_employee_ids(indx);
      commit;    
      END LOOP;

    EXCEPTION
       WHEN OTHERS
       THEN
          IF SQLCODE = -24381
          THEN
             FOR indx IN 1 .. SQL%BULK_EXCEPTIONS.COUNT
             LOOP
                 -- Caputring errors occured during update
                DBMS_OUTPUT.put_line (
                      SQL%BULK_EXCEPTIONS (indx).ERROR_INDEX
                   || ‘: ‘
                   || SQL%BULK_EXCEPTIONS (indx).ERROR_CODE);

                 --<You can inset the error records to a table here>


             END LOOP;
          ELSE
             RAISE;
          END IF;
    END;

答案 1 :(得分:0)

第二个问题,如果您只想继续更新,即使记录失败并记录错误,那么我认为您应该使用Oracle的DML错误记录子句。希望这会有所帮助。

BEGIN
  DBMS_ERRLOG.CREATE_ERROR_LOG('TAB1');
  UPDATE tab1 t1
  SET
    (
      COL1,
      COL2,
      COL3,
      COL4
    )
    =
    (SELECT COL1,COL2,COL3,COL4 FROM TAB_M WHERE ROW_ID= T1.ROW_ID
    ) LOG ERRORS REJECT LIMITED UNLIMITED;

END;