create or replace procedure proc_test( --参数区域 ) is --变量区域 --sql脚本 v_sql varchar2(2000) :=''; --记录学生数量 v_num number; begin --执行区域 -- execute immediate用法1:立刻执行sql语句 v_sql := 'create or replace view myview as select id,name from student'; execute immediate v_sql; --- execute immediate用法2:立刻执行sql语句,并赋值给某个变量 v_sql := 'select count(1) from student'; execute immediate v_sql into v_num; -- execute immediate用法3:带参数的sql v_sql:='select * from student t where t.name=:1 and t.age=:2'; execute immediate v_sql using 'zhangsan',23; end proc_test; /
拼sql还有个好处就是 v_sql:=’select * from tables t where t.c_date=:1 and t.name=:2′;
execute immediate v_sql using ‘20130304’,’xiaoming’;
可以动态的对参数传递值,这是最大的优势。
语法结构:
execute immediate dynamic_string [into {define_variable[,define_variable]…| record}] [using [in | out | in out] bind_argument[,[in | out in out] bind_argumnet]…] [{returning | return} into bind_argument[,bind_argument]…];
declare l_routin varchar2(100) := ‘gen2161.get_rowcnt’; l_tblnam varchar2(20) := ’emp’; l_cnt number; l_status varchar2(200); begin execute immediate ‘begin ‘ || l_routin || ‘(:2, :3, :4); end;’ using in l_tblnam, out l_cnt, in out l_status;
if l_status != ‘ok’ then dbms_output.put_line(‘error’); end if; end;
5. 将返回值传递到pl/sql记录类型;同样也可用%rowtype变量
declare type empdtlrec is record (empno number(4), ename varchar2(20), deptno number(2)); empdtl empdtlrec; begin execute immediate ‘select empno, ename, deptno ‘ || ‘from emp where empno = 7934’ into empdtl; end;
6. 传递并检索值.into子句用在using子句前
declare l_dept pls_integer := 20; l_nam varchar2(20); l_loc varchar2(20); begin execute immediate ‘select dname, loc from dept where deptno = :1’ into l_nam, l_loc using l_dept ; end;