四、DML(数据库操作语言)【insert、update、delete、merge(可对一个表同时执行inserts和updates操作)】
1、insert
inset into 表名(column,column,....) values(value1,value2,.....);
#第一种注意表结构中 not null的字段。
insert into 表名 values(value1,value2,.....);
#第二种要求values中的表与表结构一致,否则会报错。
**注意:**插入时会出现一些问题
-
对not null列使用null
-
违反唯一约束
-
数据类型不匹配
-
值不在列约束范围内
-
插入日期时可以使用to_date
-
例 insert into emp values (2296,'AROMANO','SALESMAN',7782, TO_DATE('2022-11-22','yyyy-mm-dd'),1300,null,10); 1 row created. select * from emp where empno=2296; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ---------- ---------- --------- ---------- --------- ---------- ---------- ---------- 2296 AROMANO SALESMAN 7782 22-NOV-22 1300 10
-
从一张表中拷贝行:
- 不能使用values
- 子查询中的列要与insert子句中的列相匹配
例
create table dept1 as select * from dept where 1=2;
Table created.
select * from dept1;
no rows selected
insert into dept1 select * from dept where deptno=10;
1 row created.
select * from dept1;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
同时向多张表插入多条数据:
insert all
into 表1 values()
into 表2 values()
into 表3 values()
.......
select ... from 表 where ...
例:向10部门和20号部门分别插入相关员工
insert all
when deptno = 10 then into emp10 values (empno,ename,deptno)
when deptno = 20 then into emp20 values (empno,ename,deptno)
select empno,ename,deptno from emp;
8 rows created.
SCOTT@prod>select * from emp10;
EMPNO ENAME DEPTNO
---------- ---------- ----------
7782 CLARK 10
7839 KING 10
7934 MILLER 10
# when 判断语句 then
这个语法就像是if 语句,例如上边的语句意思时当deptno=0时,就像emp10表内插如数据。
2、update
update from 表名 set column1='value1',column2='value2',......columnn='valuen' where condition
注意update可进行多列更新,也可以基于另一张表进行修改
例:
update emp set deptno=(select deptno from emp where empno=7369) where empno=7196;
改为空值:
1、set 属性=NULL
2、set 属性=''
where 后不能使用=NULL 、='' 、<>'' 、<>null,可以使用 is NULL 或者is NOT NULL
3、delete
delete from 表名 where 条件
注:不加where则删除表中所有数据
4、merge(不常用)
使用原始表更新目标表数据
如果存在就更新(update),不存在就插入(insert)
例:
create table test1 as select * from dept where 1=2;
create table test2 as select * from dept;
insert into test1 values (10,'DBA','BEIJING');
insert into test1 values(20,'ORACLE','SHANGHAI');
commit;
select * from test1;
DEPTNO DNAME LOC
---------- -------------- -------------
10 DBA BEIJING
20 ORACLE SHANGHAI
select * from test2;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
merge into test1 t1 using test2 t2 on (t1.deptno = t2.deptno)
2 when matched then
3 update set t1.dname=t2.dname,t1.loc=t2.loc
4 when not matched then
5 insert (deptno,dname,loc) values (t2.deptno,t2.dname,t2.loc);
select * from test1;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
40 OPERATIONS BOSTON
30 SALES CHICAGO