用批量绑定(bulk binding)的方式。当循环执行一个绑定变量的sql语句时候,在PL/SQL 和SQL引擎(engines)中,会发生大量的上下文切换(context switches)。使用bulk binding,能将数据批量的从plsql引擎传到sql引擎,从而减少上下文切换过程,提升效率。
在Oracle使用过程中经常会遇到需要插入大量数据的情况,这种情况下就可以使用Bulk Binding插入数据。
Oracle PL/SQL 优化与调整 -- Bulk 说明
参考代码:
DECLARE -- Local variables here l_date_f DATE; l_date_t DATE; TYPE t_event_id IS TABLE OF NUMBER INDEX BY BINARY_INTEGER; l_event_id t_event_id; CURSOR c_data(p_date_f DATE, p_date_t DATE) IS SELECT xe.event_id, xe.event_date, xe.application_id, xe.process_status_code FROM xla_events xe WHERE xe.application_id = 707 AND xe.process_status_code <> 'P' AND xe.event_date > p_date_f AND xe.event_date <= p_date_t; TYPE t_tab IS TABLE OF c_data%ROWTYPE; l_event t_tab; BEGIN -- Test statements here l_date_f := to_date('2008/01/01', 'yyyy/dd'); l_date_t := to_date('2017/05/31', 'yyyy/dd'); FOR i IN 1 .. (l_date_t - l_date_f) LOOP --dbms_output.put_line('l_date_f:'||to_char(l_date_f+i-1,'yyyy/dd')); --dbms_output.put_line('l_date_t:'||to_char(l_date_f+i,'yyyy/dd')); OPEN c_data(l_date_f + i - 1, l_date_f + i); LOOP FETCH c_data BULK COLLECT INTO l_event LIMIT 10000; --dbms_output.put_line(l_event.count); EXIT WHEN l_event.count = 0; FORALL j IN 1 .. l_event.count INSERT INTO xla_events_bak (application_id, event_id, event_date, event_status_code, process_status_code) VALUES (l_event(j).application_id, l_event(j).event_id, l_event(j).event_date, l_event(j).event_status_code, l_event(j).process_status_code); FORALL j IN 1 .. l_event.count UPDATE xla_events xe SET xe.process_status_code = 'P', xe.event_status_code = 'P' WHERE xe.event_id = l_event(j).event_id AND xe.application_id = l_event(j).application_id; COMMIT; END LOOP; CLOSE c_data; END LOOP; END;