[Oracle]InsertAll的妙用

无条件的插入

oracle中的insert all是指把同一批数据插入到不同的表中,假如现在有个需求:把t表中的数据分别插入t1,t2,如果你不知道insert all,你可能会使用insert插入2次,如下所示:

insert  into t1(object_name,object_id) select * from t;
insert  into t2(object_name,object_id) select * from t;
commit;

事实上,以上这种写法是错误的,因为在两次insert的过程中,t表的数据有可能已经发生了变化,也就是说,t1,t2表得到的数据有可能不一样,正确的写法应该是采用insert all: 

insert all
into t1(object_name,object_id)
into t2(object_name,object_id)
select * from t;
commit;

有条件的插入

insert first/all 是对每一行来进行判断

两者区别:

insert first:对于每一行数据,只插入到第一个when条件成立的表,不继续检查其他条件。

insert all : 对于每一行数据,对每一个when条件都进行检查,如果满足条件就执行插入操作。

看下面的例子:

--insert first
--前面等于1的条件被<=5含在内,first就表示前面插入了,后面不会再插入了。
insert first
when object_id = 1 then
into t1(object_name,object_id)
when object_id <=5 then                      
into t2(object_name,object_id)
select * from t;
commit;

select * from t1;

object_name                object_id
--------------------------------- ---
icol$                              1

select * from t2;

object_name                object_id
--------------------------------- ---
i_user1                            2
con$                               3
undo$                              4
c_cobj#                            5

--insert all
insert all
when object_id = 1 then
into t1(object_name,object_id)
when object_id <=5 then                      
into t2(object_name,object_id)
select * from t;
commit;

sql> select * from t1;

object_name                object_id
--------------------------------- ---
icol$                              1
sql> select * from t2;

object_name                object_id
--------------------------------- ---
icol$                              1
i_user1                            2
con$                               3
undo$                              4
c_cobj#                            5

行转列插入

insert all还可以实现行转列插入:

select * from sales_source_data;
employee_id    week_id  sales_mon  sales_tue  sales_wed sales_thur  sales_fri
----------- ---------- ---------- ---------- ---------- ---------- ----------
        176          6       2000       3000       4000       5000       6000

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;

select * from sales_info;
employee_id       week      sales
----------- ---------- ----------
        176          6       2000
        176          6       3000
        176          6       4000
        176          6       5000
        176          6       6000

多表插入语句的限制条件

1. 只能对表执行多表插入语句,不能对视图或物化视图执行;

2. 不能对远端表执行多表插入语句;

3. 不能使用表集合表达式;

4. 不能超过999个目标列;

5. 在rac环境中或目标表是索引组织表或目标表上建有bitmap索引时,多表插入语句不能并行执行;

6. 多表插入语句不支持执行计划稳定性;

7. 多表插入语句中的子查询不能使用序列。

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐