2014-12-08 Created By BaoXinjian
一、摘要
Oracle Insert的多种方式
1. standard insert
1. pivoting Insert
2. unconditional insert
3. conditional all insert / conditional first insert
二、标准Insert - 单表单行插入
标准Insert -- 单表单行插入
1. 语法:
INSERT INTO table [(column1,column2,...)] VALUE (value1,value2,...)
2. 示例:
INSERT INTO dep (dep_id,dep_name) VALUES(1,'技术部');
3. 备注:
用标准语法只能插入一条数据,且只能在一张表中插入数据
三、无条件 Insert All - 多表多行插入
无条件 Insert all -- 多表多行插入
1. 语法:
INSERT [ALL] [condition_insert_clause]
[insert_into_clause values_clause] (subquery)
2. 示例:
INSERT ALL
INTO sal_history(emp_id,hire_date,salary) values (empid,hiredate,sal) INTO mgr_history(emp_id,manager_id,salary) values (empid,hiredate,sal) SELECT employee_id empid,hire_date hiredate,salary sal,manager_id mgr FROM employees WHERE employee_id>200;
四、有条件的Insert
有条件的Insert
1. 语法:
INSERT [ALL | FIRST]
WHEN condition THEN insert_into_clause values_clause
[WHEN condition THEN] [insert_into_clause values_clause]
......
[ELSE] [insert_into_clause values_clause]
Subquery;
2. 示例:
INSERT All
WHEN id>5 THEN INTO z_test1(id, name) VALUES(id,name) WHEN id<>2 THEN INTO z_test2(id) VALUES(id) ELSE INTO z_test3 VALUES (name) SELECT id,name FROM z_test;
当使用ALL关键字时,oracle会从上至下判断每一个条件,当条件满足时就执行后面的into语句
在上面的例子中,如果ID=6 那么将会在z_test1中插入一条记录,同时也在z_test2中插入一条记录
3. 备注:
当使用FIRST关键字时,oracle会从上至下判断每一个条件,当遇到第一个满足时就执行后面的into语句,
同时中断判断的条件判断,在上面的例子中,如果ID=6,仅仅会在z_test1中插入一条数据
五、旋转Pivoting Insert
旋转Insert (pivoting insert)
create table sales_source_data ( employee_id number(6), week_id number(2), sales_mon number(8,2), sales_tue number(8,2), sales_wed number(8,2), sales_thur number(8,2), sales_fri number(8,2) ); insert into sales_source_data values (176,6,2000,3000,4000,5000,6000); create table sales_info ( employee_id number(6), week number(2), sales number(8,2) );
看上面的表结构,现在将要sales_source_data表中的数据转换到sales_info表中,这种情况就需要使用旋转Insert
2. 示例如下:
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;
3. 从该例子可以看出,所谓旋转Insert是无条件 insert all 的一种特殊应用,但这种应用被oracle官方,赋予了一个pivoting insert的名称,即旋转insert
Thanks and Regards