oracle execute immediate


解析并马上执行动态语句 ,或非运行时创建的pl/sql块

1. 不提交dml事务,要显式提交;
execute immediate处理ddl,会提交所以以前改变的数据;

2.不支持多行查询,可以临时表 或者ref cursors

3.执行sql不需语句,执行pl/sql 要加分号;

--0.传入
declare
	i_aac001 number(6):=111;
begin
	execute immediate 'insert into a2(aac001) values(:1)'
	using i_aac001; 
end;


insert into a2(aac001) values(1);
insert into a2(aac001) values(2);


--1.传入/传出
declare
	cnt number(6);
begin
	execute immediate 'select 1 from dual where 1=:1' into cnt
	using cnt;
	dbms_output.put_line(cnt);
end;

--2.调用存储过程
declare
	s1 varchar2(10);
	s2 varchar2(10);
begin
	execute immediate 'begin test1(:1,:2); end;'
	using s1,s2;
end;

--3.传值到记录
declare
--类型
--声明
	type type_a is record(str varchar2(10));
	v_a type_a;
	v_b a2%rowtype;
begin
	execute immediate 'select * from a2 where aac001=1742178' 
	into v_b;
end;

--4.多行查询 用临时表 或ref cursors
declare 
   l_sal    pls_integer := 2000; 
begin 
   execute immediate 'insert into temp(empno, ename) ' || 
                    '           select empno, ename from emp ' || 
                    '           where   sal > :1' 
     using l_sal; 
   commit; 
end; 

http://baiyaoming.iteye.com/blog/1255016


for in  变量声明类型
-------------------------------
declare
cursor cur is select * from a2;
begin
	for c in (select * from a2) loop
		dbms_output.put_line(c.aac002);
	end loop;
end;

insert into a2(aac001) values(1);

declare
	type t_a is table of a2%rowtype;
	type t_b is table of number(10) index by pls_integer;
	v_a t_a;
	v_b t_b;
begin
	select aac001 bulk collect into v_b from a2;
	for i in v_b.first..v_b.last loop
		dbms_output.put_line(v_b(i));
	end loop;
end;



猜你喜欢

转载自kevinlee0755.iteye.com/blog/1381617