一、使用动态游标实现 1、声明动态游标 TYPE i_cursor_type IS REF CURSOR; 2、声明游标变量 my_cursor i_cursor_type; 3、使用游标 n_deptno:=20; dyn_select := 'select empno,ename from emp where deptno='||n_deptno; OPEN my_cursor FOR dyn_select; LOOP FETCH my_cursor INTO n_empno,v_ename; EXIT WHEN my_cursor%NOTFOUND; --用n_empno,v_ename做其它处理 --.... END LOOP; CLOSE dl_cursor; 4、小结:动态游标可以胜任大多数动态SQL的需求了,使用简洁方便居家旅行之必备杀人放火之法宝。
declare l_depnam varchar2(20) := 'testing'; l_loc varchar2(10) := 'Dubai'; begin execute immediate 'insert into dept values (:1, :2, :3)' using 50, l_depnam, l_loc; commit; end;
3. 从动态语句检索值(INTO子句)
declare l_cnt varchar2(20); begin execute immediate 'select count(1) from emp' into l_cnt; dbms_output.put_line(l_cnt); end;
4. 动态调用例程.例程中用到的绑定变量参数必须指定参数类型.黓认为IN类型,其它类型必须显式指定
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;