详解Oracle中一条insert语句同时插入多张表

1.Oralce官方文档参考链接

http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9014.htm#SQLRF01604

2、创建源表STUINFO,并插入几条测试数据

create table stuInfo(
             id number,
             name varchar2(60),
             sex varchar2(10),
             age number(3));

insert into stuInfo values(1001,'KevinMa','F',28);
insert into stuInfo values(1002,'Merry','M',18);
insert into stuInfo values(1003,'Ketty','M',16);
insert into stuInfo values(1004,'King','F',28);
commit;

3、创建目标表aa,bb

create table aa as select * from stuInfo where 1=0;
create table bb as select * from stuInfo where 1=0;

4、将源表STUINFO中的数据分别全部插入目标表aa、bb中

insert all 
    into aa values
     (id, name, sex, age) 
    into bb values
     (id, name, sex, age)
  select id, name, sex, age from stuInfo;

通过如下SQL验证aa、bb表数据

select 'AA' AS TABLE_NAME,a.* from aa a
  union all
select 'BB' AS TABLE_NAME,b.* from bb b

5、按照条件将SEX=F插入表AA,SEX=M插入表BB

insert all
  when sex = 'F' then
    into aa
  when sex = 'M' then
    into bb
select * from stuinfo;
--或者
insert all
when sex = 'F' then
 into aa
else
 into bb
select * from stuinfo;

扫描二维码关注公众号,回复: 5975034 查看本文章

6、First用法,源表的每条记录只会被插入一次,即使满足多个条件也只插入一次

---first
insert first
  when sex = 'M' then
    into aa
  when age>=18 then
    into bb
select * from stuinfo;
----all
insert all
  when sex = 'M' then
    into aa
  when age>=18 then
    into bb
select * from stuinfo;

FIRST的结果
ALL的结果

 Good Luck

猜你喜欢

转载自blog.csdn.net/makai5521/article/details/89359068