多表insert操作詳解


--1.無條件的多表insert all
create table emp_1 as select id,last_name from s_emp where 1=0;
create table emp_2 as select * from s_emp where 1=0;
create table emp_3 as select * from s_emp where 1=0;
--沒有條件,向多個目標表全量插入,必須有all
insert all
--不指定emp_1后面的列,也不指定values,那么emp_1中的所有列類型和順序與查詢的列的類型和順序一致
--也就是emp_1中只有查詢結果中的那幾列,而且類型和順序與其一致
into emp_1
--指定了emp_2后面的列,沒有values,表示emp_2中要插入的列被選擇出來,與查詢的結果列類型和順序一致
--emp_2中也可能有很多列,不止這兩列
into emp_2(id,last_name)
--指定emp_3后面的列,也指定values,那么values后面的列名必須與查詢結果一致,如果
--查詢中有別名,必須在values中使用別名。emp_3中指定的列類型和順序必須與values保持一致
--emp_3中也可能列數大於指定的列數
into emp_3(id,last_name) values(s_id,s_last_name)
select id s_id,last_name s_last_name
  from s_emp;

--2.帶條件的多表insert all
--conditional insert all:all可以省略,但不建議.
insert all
--將查詢結果中為s_id>20的插入,條件中指定的列必須與查詢的結果名字一致,如果有別名,用別名
when s_id>20 then
into emp_1
--s_last_name為M開頭的插入,可能插入的行與s_id>20有重復
when s_last_name like 'M%'then
into emp_2(id,last_name)
--如果指定else,則不滿足上面兩個條件的插入到emp_3,插入的行不會與上面兩個重復
else
into emp_3(id,last_name) values(s_id,s_last_name)
select id s_id,last_name s_last_name
  from s_emp;
  
--3.帶條件的多表insert first
--Insert first只有帶條件的,沒有不帶條件的。
--語法只要將insert all中的all改為first就可以了。這里的first不可以省略。省略那么默認就是all
insert first
--將查詢結果中為s_id>20的插入,條件中指定的列必須與查詢的結果名字一致,如果有別名,用別名
when s_id>20 then
into emp_1
--s_last_name為M開頭的插入,插入的行與s_id>20沒有重復
when s_last_name like 'M%'then
into emp_2(id,last_name)
--如果指定else,則不滿足上面兩個條件的插入到emp_3,插入的行不會與上面兩個重復
else
into emp_3(id,last_name) values(s_id,s_last_name)
select id s_id,last_name s_last_name
from s_emp;

--4.選擇插入Pivoting insert
--使用pivoting insert實現將非關系性表記錄轉換為關系型表中存儲。Pivot旋轉是OLAP中的一個基本改變,提供多維度數據分析。
insert all
into sales_info values(employee_id,week_id,sales_mon) --分別按每個工作日插入
into sales_info values(employee_id,week_id,sales_tue)
into sales_info values(employee_id,week_id,sales_wed)
into sales_info values(employee_id,week_id,sales_thur)
into sales_info values(employee_id,week_id,sales_fri)
select employee_id,week_id,sales_mon,sales_tue,sales_wed,sales_thur,sales_fri
from sales_source_data;

多表insert使用限制:
1. 只能對table使用多表insert,不能對視圖或物化視圖使用。
2. 不能對遠程表進行這個插入操作。
3. 在做多表insert操作,不能指定一個表的集合表達式。
4. 多表insert中的的into目標表加在一起的列數不能超過999 個。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM