oracle SQL引擎和PL/SQL引擎

如下圖所示,PL/SQL引擎會執行過程化語句,但它把SQL語句發送給SQL引擎處理,然後SQL引擎把處理的結果返回給PL/SQL引擎。




PL/SQL和SQL引擎間的頻繁切換會大大降低效率。典型的情況就是在一個循環中反覆執行SQL語句。例如,下面的DELETE語句就會在FOR循環中被多次發送到SQL引擎中去:


初始化一些數據:

create table emp
(
  emp_id int primary key,
  deptno int not null
);

declare
l_deptno int;
begin
  for i in 1..1000000 loop
    l_deptno := i mod 4;
    insert into emp values (i, l_deptno);
  end loop;
  commit;
end;

測試1:

SQL> declare
  2    type numlist is array(20) of number;
  3    depts numlist := numlist(0,1,2,3);
  4  begin
  5    for i in depts.first .. depts.last loop
  6      delete from emp where deptno = depts(i);
  7    end loop;
  8    commit;
  9  end;
 10  /

PL/SQL 過程已成功完成。

已用時間:  00: 00: 48.93

測試2:

SQL> declare
  2    type numlist is array(20) of number;
  3    depts numlist := numlist(0,1,2,3);
  4  begin
  5    forall i in depts.first .. depts.last
  6      delete from emp where deptno = depts(i);
  7    commit;
  8  end;
  9  /

PL/SQL 過程已成功完成。

已用時間:  00: 00: 54.21

關鍵字FORALL能讓PL/SQL引擎在將集合發送到SQL引擎之前,批量導入集合元素。雖然FORALL也包含了迭代的模式,但它並不是簡單的FOR循環。


《PLSQL用戶指南與參考》這本書裏是這樣寫的,可是測試下來,並不是那樣的。

發佈了455 篇原創文章 · 獲贊 40 · 訪問量 137萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章