创建测试表
CREATE TABLE t1
AS
SELECT mod(LEVEL,1000) ID,LEVEL+1000 sal,MOD(LEVEL,10) ext
FROM dual
CONNECT BY LEVEL<10000;
create table t2(id number(18),sal number(18),ext number(18));
create table t3(id number(18),sal number(18),ext number(18));
create table t4(id number(18),sal number(18),ext number(18));
SQL> select count(*) from t1;
COUNT(*)
----------
9999
SQL> select count(*) from t2;
COUNT(*)
----------
0
SQL> select count(*) from t3;
COUNT(*)
----------
0
SQL> select count(*) from t4;
COUNT(*)
----------
0
现在我们使用 insert all
SQL> insert All
2 when rn <2000 then
3 into t2(id,sal,ext) values ( id,sal,ext )
4 when rn >=2000 And rn <8000 then
5 into t3(id,sal,ext) values ( id,sal,ext )
6 when rn >6000 then
7 into t4(id,sal,ext) values ( id,sal,ext )
8 select rn,id,sal,ext from( select rownum rn ,t1.* from t1 ) a
9 ;
11998 rows inserted
SQL> select count(*) from t2;
COUNT(*)
----------
1999
SQL> select count(*) from t3;
COUNT(*)
----------
6000
SQL> select count(*) from t4;
COUNT(*)
----------
3999
SQL>
在 into t4的时候 我们发现rn 的值,其实和into t3的部分有交集。
但是我们发现 insert all是把交集部分也插入到了t4里面。
那我们采用insert first 来看看它的效果.
SQL> truncate table t2;
Table truncated
SQL> truncate table t3;
Table truncated
SQL> truncate table t4;
Table truncated
SQL> select count(*) from t2;
COUNT(*)
----------
0
SQL> select count(*) from t3;
COUNT(*)
----------
0
SQL> select count(*) from t4;
COUNT(*)
----------
0
下面我们采用insert first
SQL> insert first
2 when rn <2000 then
3 into t2(id,sal,ext) values ( id,sal,ext )
4 when rn >=2000 And rn <8000 then
5 into t3(id,sal,ext) values ( id,sal,ext )
6 when rn >6000 then
7 into t4(id,sal,ext) values ( id,sal,ext )
8 select rn,id,sal,ext from( select rownum rn ,t1.* from t1 ) a
9 ;
9999 rows inserted
SQL> select count(*) from t2;
COUNT(*)
----------
1999
SQL> select count(*) from t3;
COUNT(*)
----------
6000
SQL> select count(*) from t4;
COUNT(*)
----------
2000
SQL>
发现我们用insert first 时 会自动把 rn >6000 And rn <8000 的数据自动取消掉。
其实oracle insert first
1、Oracle 服务器对每一个出现在语句顺序中的 WHEN 子句求值;
2、如果第一个 WHEN 子句的值为 true,Oracle 服务器对于给定的行执行相应的 INTO 子句,并且跳过后面的 WHEN 子句(后面的when语句都不再考虑满足第一个When子句的记录,即使该记录满足when语句中的条件)。