从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 中,变量绑定的常见用法基本如上所示,建议全部使用变量绑定。