7.2.2
使用子查询更新记录
相关子查询:
update emp x
set x.sal = (select avg(y.sal)
from emp y
where y.deptno = x.deptno
)
where x.empno = 7386;
非相关子查询:
update emp
set sal = (select sal
from emp
where empno=7782
)
where empno = 7369
使用子查询更新多个列:
update emp x
set ( x.sal,x.comm) = ( select avg(y.sal),max(y.comm)
from emp y
where y.deptno = x.deptno
)
where x.empno = 7369
多表关联的形式进行更新:
update (select x.sal sal, y.sal sal_history,x.comm comm,y.comm comm_history
from emp x,emp_history y
where x.empno = y.empno
and x.empno = 7369
)
set sal_history = sal,
comm_history = comm;
以上语句可能出现两个相同的empno编号:
可以使用Oracle的Hint进行更新:
update /×+bypass_ujvc×/ (select x.sal sal, y.sal sal_history,x.comm comm,y.comm comm_history
from emp x,emp_history y
where x.empno = y.empno
and x.empno = 7369
)
set sal_history = sal,
comm_history = comm;
7.2.3使用merge合并表行使用该语句可以有条件地更新和插入数据到数据库表中,对数据表进行插入时,如果行存在,则执行update语句进行更新;如果是一个新行,则执行insert语句进行插入
merge into table_name table_alias
using (table|view|sub_query) alias
on (join condition)
when mathed then
update set
col1 = col_val1,
col2 = col2_val
when not mathed then
insert ( column_list)
values(column_values);
merge into :指定正在更新或者插入的目标行
using :指定数据源要被更新或者插入的数据的来源,数据的来源可以是表,视图或者一个子查询
on 子句:后跟条件从句,指定merger操作可以更新或者插入
when matched| when not matched:指定当匹配时,应当执行update子句进行更新,当不匹配时,应执行insert语句进行插入
merge into emp_copy c --目标表
using emp e --源表,可以是表,视图,子查询
on ( c.empno = e.empno)
when matched then
update
set c.ename = e.ename,
c.job = e.job,
c.mgr = e.mgr,
.....
when not matched then
insert
values( )
删除数据:
delete from emp x
where exists (
select 1
from emp_copy
where empno = x.empno
)
7.3.3 TRUNCATE清除表数据
一经调用,表中的数据便被清除,
与DELETE语句相比,使用TRUNCATE命令速度要快一些,这是由于以下3个原因,
TRUNCATE语句不会激活表的删除触发器
TRUNCATE语句数据定义语言DDL语句,不会产生撤销信息
如果表示主外键关系的主表,则无法清除表的内容,必须在执行TRUNCATE语句之前禁用该约束
注:TRUNCATE属于DDL语句,因此不能被PL/SQL语句块直接调用,必须要使用动态语句调用方式
如果清除dept表时,dept表与emp表具有主外键关系,Oracle会弹出错误提示,为了能正确地清除表内容,必须首先禁用在dept上定义的约束,
然后使用TRUNCATE TABLE进行表内容的清除,
alert table dept disable constraint pk_dept cascade;
truncate table dept;