5544992 发表于 2018-9-23 13:16:57

oracle的多表插入

Q5,oracle的多表插入操作。在业务处理过程中,经常会碰到将业务数据按照条件分别插入不同的数据表的问题,按照传统的处理方式,需要分条件执行多次检索后分别插入不同的表单,这样因为执行了重复的检索造成cpu和内存的浪费,从oracle9i开始引入了insert all关键字支持将某张表的数据同时插入多张表单。语法如下:  Insert all Insert_into_clause subquery;
  Insert conditional_insert_clause subquery;
  如上所示,insert_into_clause用于指定insert子句;value clause用于指定值子句;subquery用于指定提供数据的子查询;condition_insert_clause用于指定insert条件子句。
  当使用all操作符执行多表插入时,在每个条件子句上都要执行into子句后的子查询,并且条件中使用的列必须在插入和子查询的结果集中:
  --创建测试用表
  createtable tdate(
  idvarchar2(10),
  namevarchar2(20),
  birthday datedefaultsysdate
  );
  --插入数据
  insertinto tdate values(1,'zhangsan',to_date('1980-05-10','YYYY-MM-DD'));
  insertinto tdate values(1,'zhangsan',to_date('1980-05-10','YYYY-MM-DD'));
  insertinto tdate values(2,'lisi',to_date('1980-05-10','YYYY-MM-DD'));
  insertinto tdate values(3,'wangwu',default);
  insertinto tdate(id,name) values(4,'zhangsan');
  commit;
  --创建接收用测试表
  createtable tdate1 asselect * from tdate where1=0;
  createtable tdate2 asselect * from tdate where1=0;
  commit;
  --使用all关键字执行多表插入操作
  insertall
  when birthday > '01-1月-08'theninto tdate1
  when birthday < '01-1月-08'theninto tdate2
  whenname = 'zhangsan'theninto tdate1
  whenname = 'lisi'theninto tdate2
  select * from tdate;
  在上述操作语句中,如果原表tdate中存在既满足birthday > '01-1月-08'又满足name = 'zhangsan'的数据,那么将执行两次插入。而使用first关键字就可以避免这个问题。使用first关键字时,如果有记录已经满足先前条件,并且已经被插入到某个表单中(未必非要是同一个表),那么该行数据在后续插入中将不会被再次使用。也就是说使用first关键字,原表每行数据按照执行顺序只会被插入一次。
  insertfirst
  when birthday > '01-1月-08'theninto tdate1
  when birthday < '01-1月-08'theninto tdate2
  whenname = 'zhangsan'theninto tdate1
  whenname = 'lisi'theninto tdate2
  select * from tdate;

页: [1]
查看完整版本: oracle的多表插入