多表的insert语句
- 语法
INSERT [ALL] [conditional_insert_clause] [insert_into_clause values_clause] (subquery)
- conditional_insert_clause
[ALL] [FIRST] [WHEN condition THEN] [insert_into_clause values_clause] [ELSE] [insert_into_clause values_clause]
无条件的 INSERT ALL
insert all
into test1 (empno,ename) values(empno,ename)
into test1(ename,sal) values(ename,sal)
select * from emp;
有条件的INSERT ALL语句(对于每一行数据,对每一个when条件都进行检查,如果满足条件就执行插入操作)
-- 有条件的INSERT ALL语句
insert all
when sal>1000 then
into test1 (empno,sal,mgr) values (empno,sal,mgr)
when comm<500 then
into test1 (empno,comm,mgr) values(empno,comm,mgr)
select empno,sal,mgr,comm
from emp;
有条件的 FIRST INSERT语句(对于每一行数据,只插入到第一个when条件成立的表,不继续检查其他条件)
-- 有条件的 FIRST INSERT语句
-- 对于每一行数据,只插入到第一个when条件成立的表,不继续检查其他条件。
insert first
when sal>1000 then
into test1 (empno,sal,mgr) values (empno,sal,mgr)
when comm<500 then
into test1 (empno,comm,mgr) values(empno,comm,mgr)
select empno,sal,mgr,comm
from emp;
INSERT ALL 和INSERT FIRST对比
SQL> -- 有条件的INSERT ALL语句
SQL> insert all
2 when sal>1000 then
3 into test1 (empno,sal,mgr) values (empno,sal,mgr)
4 when comm<500 then
5 into test1 (empno,comm,mgr) values(empno,comm,mgr)
6 select empno,sal,mgr,comm
7 from emp;
已创建14行。
SQL> -- 有条件的 FIRST INSERT语句
SQL> -- 对于每一行数据,只插入到第一个when条件成立的表,不继续检查其他条件。
SQL> insert first
2 when sal>1000 then
3 into test1 (empno,sal,mgr) values (empno,sal,mgr)
4 when comm<500 then
5 into test1 (empno,comm,mgr) values(empno,comm,mgr)
6 select empno,sal,mgr,comm
7 from emp;
已创建12行。
旋转INSERT (行转列插入)
-- 旋转INSERT (行转列插入)
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_source_data;
EMPLOYEE_ID WEEK_ID SALES_MON SALES_TUE SALES_WED SALES_THUR SALES_FRI
----------- ---------- ---------- ---------- ---------- ---------- ----------
176 6 2000 3000 4000 5000 6000
-- 转存后的表
select * from sales_info;
EMPLOYEE_ID WEEK SALES
----------- ---------- ----------
176 6 2000
176 6 3000
176 6 4000
176 6 5000
176 6 6000