绑定变量(bind variable)我们经常在写plsql中用到,那我们承接上一节的来看看在plsql中静态sql和动态sql在绑定变量的区别
declare
v_value_a varchar2(100);
v_value_b varchar2(100);
v_name varchar2(50);
begin
v_value_a := 'SMITH';
select e.ename/*+test*/into v_name from scott.emp e where e.ename = v_value_a;
v_value_b := 'ALLEN';
select e.ename/*+test*/into v_name from scott.emp e where e.ename = v_value_b;
end;
/
查询v$sql
select * from v$sql d where d.SQL_TEXT like '%/*+test*/%';

这里看到只产生了一条sql_id,oracle会自动把变量v_value_a,v_value_b换成绑定变量:B1.
再来看看动态sql
PLSQL_1:
declare
v_value_a varchar2(100);
v_value_b varchar2(100);
v_name varchar2(50);
begin
v_value_a := 'SMITH';
v_value_b := 'ALLEN';
execute immediate 'select e.ename/*+sql*/ from scott.emp e where e.ename = :xxx'
using v_value_a;
execute immediate 'select e.ename/*+sql*/ from scott.emp e where e.ename = :yyy'
using v_value_b;
end;
/
查询v$sql
select * from v$sql d where d.SQL_TEXT like '%/*+sql*/%';

这里可以看到动态sql就是以执行sql为文本进行解析的,如果两个sql有不同就是不同的sql语句。
2.获取绑定变量的值
那我们可以得到绑定的变量的值吗?通过v$sql_bind_capture就可以查询到
SQL_1:
select d.NAME, d.POSITION, d.SQL_ID, value_string
from v$sql_bind_capture d
where d.SQL_ID in
(select sql_id from v$sql v where v.SQL_TEXT like '%/*+sql*/%')

这时我们看到绑定变量的值是上文看到的v_value_a和v_value_b的值。
接着往下走,改变v_value_a的值:
v_value_a := 'CLARK';
执行PLSQL_1,SQL_1

绑定变量的值并没有发生变化,这时为什么呢?