1.創建表T並初始化測試數據,此表作爲數據源。
sec@ora10g> create table t (x number(10), y varchar2(10));
sec@ora10g> insert into t values (1,'a');
sec@ora10g> insert into t values (2,'b');
sec@ora10g> insert into t values (3,'c');
sec@ora10g> insert into t values (4,'d');
sec@ora10g> insert into t values (5,'e');
sec@ora10g> insert into t values (6,'f');
sec@ora10g> commit;
2.查看錶T的數據
sec@ora10g> select * from t;
X Y
---------- ----------
1 a
2 b
3 c
4 d
5 e
6 f
6 rows selected.
3.創建表T1和T2,作爲我們要插入的目標表。
sec@ora10g> create table t1 as select * from t where 0=1;
Table created.
sec@ora10g> create table t2 as select * from t where 0=1;
Table created.
4.第一種多表插入方法INSERT ALL
1)完成INSERT ALL插入
sec@ora10g> insert all into t1 into t2 select * from t;
12 rows created.
這裏之所以顯示插入了12條數據,實際上表示在T1表中插入了6條,T2表插入了6條,一共是12條數據。
2)驗證T1表中被插入的數據。
sec@ora10g> select * from t1;
X Y
---------- ----------
1 a
2 b
3 c
4 d
5 e
6 f
6 rows selected.
3)驗證T2表中被插入的數據。
sec@ora10g> select * from t2;
X Y
---------- ----------
1 a
2 b
3 c
4 d
5 e
6 f
6 rows selected.
OK,完成INSERT ALL命令的使命。
5.第二種多表插入方法INSERT FIRST
1)清空表T1和T2
sec@ora10g> delete from t1;
sec@ora10g> delete from t2;
sec@ora10g> commit;
2)完成INSERT FIRST插入
sec@ora10g> insert first when x>=5 then into t1 when x>=2 then into t2 select * from t;
5 rows created.
處理邏輯是這樣的,首先檢索T表查找X列值大於等於5的數據(這裏是“5,e”和“6,f”)插入到T1表,然後將前一個查詢中出現的數據排除後再查找T表,找到X列值大於等於2的數據再插入到T2表(這裏是“2,b”、“3,c”和“4,d”)。注意INSERT FIRST的真正目的是將同樣的數據只插入一次。
3)驗證T1表中被插入的數據。
sec@ora10g> select * from t1;
X Y
---------- ----------
5 e
6 f
4)驗證T2表中被插入的數據。
sec@ora10g> select * from t2;
X Y
---------- ----------
2 b
3 c
4 d
5)爲真實的反映“數據只插入一次”的目的,我們把條件顛倒後再插入一次。
sec@ora10g> delete from t1;
sec@ora10g> delete from t2;
sec@ora10g> insert first when x>=2 then into t1 when x>=5 then into t2 select * from t;
5 rows created.
sec@ora10g> select * from t1;
X Y
---------- ----------
2 b
3 c
4 d
5 e
6 f
sec@ora10g> select * from t2;
no rows selected
OK,目的達到,可見滿足第二個條件的數據已經包含在第一個條件裏,所以不會有數據插入到第二張表。
同樣的插入條件,我們把“INSERT FIRST”換成“INSERT ALL”,對比一下結果。
sec@ora10g> delete from t1;
5 rows deleted.
sec@ora10g> delete from t2;
0 rows deleted.
sec@ora10g> insert all when x>=2 then into t1 when x>=5 then into t2 select * from t;
7 rows created.
sec@ora10g> select * from t1;
X Y
---------- ----------
2 b
3 c
4 d
5 e
6 f
sec@ora10g> select * from t2;
X Y
---------- ----------
5 e
6 f
是不是在豁然開朗的基礎上又有一種錦上添花的感覺。That's it.
6.Oralce官方文檔參考鏈接
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9014.htm#SQLRF01604
7.小結
這些小小小的高級SQL技巧在實際的應用中有很大用處。慢慢體會吧。
Good luck.
secooler
10.01.06
-- The End --