一、插入新记录
建立测试表,各列都有默认值。
CREATE TABLE TEST(
c1 VARCHAR2(10) DEFAUT'默认1',
c2 VARCHAR2(10) DEFAUT'默认2',
c3 VARCHAR2(10) DEFAUT'默认3',
c4 DATE DEFAULT SYSDATE);
新增数据如下:
INSERT INTO TEST(c1,c2,c3) VALUES(DEFAULT,NULL,'手输值');
SELECT * FROM TEST;
C1 C2 C3 C4
------ ------ ------ ------
默认1 手输值 2017-08-07
1 row selected
可以看出几点
1、如果INSERT语句中没有含默认值的列,则会添加默认值,如C4列。
2、如果含默认值的列,使用DEFAULT关键字,都会添加默认值,如C1列。
3、如果设置了值如NULL可其它,则不会再生成默认值,如C2、C3列。
二、多表插入语句
多表插入分为以下四种
1、无条件INSERT
2、有条件 INSERT ALL
3、转置INSERT
4、有条件INSERT ALL
建立测试用表
CREATE TABLE emp1 AS SELECT empno,ename,job FROM emp WHERE 1=2;
CREATE TABLE emp2 AS SELECT empno,ename,deptno FROM emp WHERE 1=2;
无条件INSERT
INSERT ALL
INTO emp1(empno,ename,job)VALUES(empno,ename,job)
INTO emp2(empno,ename,deptno)VALUES(empno,ename,deptno)
SELECT impno,ename,job,deptno FROM emp WHERE deptno IN(10,20);
这样会同时向两张表中插入数据,且两个表中插入的数据条数是一样的
有条件 INSERT ALL
delete emp1;
delete emp2;
INSERT ALL
WITH job IN('SALESMAN','MANAGER') THEN
INTO emp1(empno,ename,job)VALUES(empno,ename,job)
WITH deptno IN('20','30') THEN
INTO emp2(empno,ename,deptno)VALUES(empno,ename,deptno)
SELECT impno,ename,job,deptno FROM emp
这样会按条件插入
INSERT FIRST
delete emp1;
delete emp2;
INSERT FIRST
WITH job IN('SALESMAN','MANAGER') THEN
INTO emp1(empno,ename,job)VALUES(empno,ename,job)
WITH deptno IN('20','30') THEN
INTO emp2(empno,ename,deptno)VALUES(empno,ename,deptno)
SELECT impno,ename,job,deptno FROM emp
当第一个表符合条件后,第二个表将不再插入对应的行,emp1和emp2不再会有相同的数据
转置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
示例如下:
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;
部分选自《Oracle 查询优化改写技巧与案例》 有教无类 落落 著