天天看點

oracle的多表插入

  Q5 ,oracle 的多表插入操作。在業務處理過程中,經常會碰到将業務資料按照條件分别插入不同的資料表的問題,按照傳統的處理方式,需要分條件執行多次檢索後分别插入不同的表單,這樣因為執行了重複的檢索造成cpu和記憶體的浪費,從oracle9i開始引入了insert all關鍵字支援将某張表的資料同時插入多張表單。文法如下: Insert all Insert_into_clause [value_clause] subquery; Insert conditional_insert_clause subquery; 如上所示,insert_into_clause用于指定insert子句;value clause用于指定值子句;subquery用于指定提供資料的子查詢;condition_insert_clause用于指定insert條件子句。 當使用all操作符執行多表插入時,在每個條件子句上都要執行into子句後的子查詢,并且條件中使用的列必須在插入和子查詢的結果集中: -- 建立測試用表 create table tdate( id varchar2 ( 10 ), name varchar2 ( 20 ), birthday date default sysdate ); -- 插入資料 insert into tdate values ( 1 , 'zhangsan' ,to_date( '1980-05-10' , 'YYYY-MM-DD' )); insert into tdate values ( 1 , 'zhangsan' ,to_date( '1980-05-10' , 'YYYY-MM-DD' )); insert into tdate values ( 2 , 'lisi' ,to_date( '1980-05-10' , 'YYYY-MM-DD' )); insert into tdate values ( 3 , 'wangwu' , default ); insert into tdate( id , name ) values ( 4 , 'zhangsan' ); commit ; -- 建立接收用測試表 create table tdate1 as select * from tdate where 1 = 0 ; create table tdate2 as select * from tdate where 1 = 0 ; commit ; -- 使用 all 關鍵字執行多表插入操作 insert all when birthday > '01-1 月 -08' then into tdate1 when birthday < '01-1 月 -08' then into tdate2 when name = 'zhangsan' then into tdate1 when name = 'lisi' then into tdate2 select * from tdate; 在上述操作語句中,如果原表tdate中存在既滿足 birthday > '01-1 月 -08' 又滿足 name = 'zhangsan' 的資料,那麼将執行兩次插入。而使用 first 關鍵字就可以避免這個問題。使用 first 關鍵字時,如果有記錄已經滿足先前條件,并且已經被插入到某個表單中(未必非要是同一個表),那麼該行資料在後續插入中将不會被再次使用。也就是說使用 first 關鍵字,原表每行資料按照執行順序隻會被插入一次。 insert first when birthday > '01-1 月 -08' then into tdate1 when birthday < '01-1 月 -08' then into tdate2 when name = 'zhangsan' then into tdate1 when name = 'lisi' then into tdate2 select * from tdate;