從Oracle的共用池的設計、和Oracle推薦的 PL/SQL 寫法中,可以看出,變數綁定對效能有比較大的影響,那麼,如何在PL/SQL 中使用變數綁定呢?
首先看看不使用變數綁定的用法:
declare
cursor cur_temp(id number) is
select * from table_a where a=id;
c_temp cur_temp%rowtype;
beign
open cur_temp(1);
loop
fetch cur_temp into c_temp;
exit when cur_temp%notfound;
insert into b values (c_temp.a);
end loop;
close cur_temp;
commit;
end;
上面是沒有使用變數綁定的用法,包括遊標和動作陳述式。
再看下面使用變數綁定的用法:
先要
type cursorType is ref cursor;
然後:
declare
cur_temp cursortype;
c_temp table_a%rowtype;
begin
open cur_temp for 'select * from table_a where a=:1' using 91;
loop
fetch cur_temp into c_temp;
exit when cur_temp%notfound;
execute immediate 'insert into b values (:1)' using c_temp.a;
end loop;
close cur_temp;
commit;
end;
上面是在PL/SQL 塊中的寫法,這個寫法也同樣適用於預存程序,觸發器,函數,包等可以用PL/SQL 的地方。
對於需要用 INTO 的地方,可以如下使用:
i number(6);
execute immediate 'select count(*) from table_a where a =:1' into i using 89;
執行後,取出的值存放在了變數 i 中。
在PL/SQL 中,變數綁定的常見用法基本如上所示,建議全部使用變數綁定。