注:update操作时,条件必须注意。不写where即为更新全表,不想更新的会被赋空值。
单表更新:update tablename set col1=value where col2='value2';
多表关联更新:update a set a.col1=(select b.col1 from b where a.col2=b.col2) where exists(select * from b where a.col2=b.col2); --exists条件必须要有,不然更新有误
多字段更新:update a set (a.col1,a.col2) = (select b.col1,b.col2 from b where b.col3=a.col3 and b.col4=value2) where exists (select 1 from b where b.col3=a.col3 and b.col4=value2); --同样必须加条件,无where则为全表更新,不满足条件的为空。
update a set a.col1=100 将所有行全部的特定列col1更新为特定值
update a set a.col1=100 where a.col2<10 将满足col2条件的行的col1列的值更新为特定的值
update a set a.col1=a.col1+a.col2 where a.col2<10 同一个表中的简单计算更新
update a set a.col1=(select b.col1 from b where a.col2=b.col2)
where exists(select * from b where a.col2=b.col2) 级联更新,将满足a.col2=b.col2的行的a.col1更新为对应的
b.col1的值。当且仅当a=b时可以将where条件去掉。这个更新还可以这样理解:
update a set a.col1=(select b.col1 from b where a.col2=b.col2)表示对于a中所有行满足a.col2=b.col2
的进行更新,不满足条件的也更新,只不过找不到对应的值,只能将空值赋之,如果此时a.col1不允许为空那么会报插入空值错误。
所以只有加上where条件,才能将a.col2<>b.col2的那些在a中的数据得以幸存(不被更新为空)。
inline view更新法就是更新一个临时建立的视图
update (select a.state as state_a,b.state as state_b from a,b where a.col1=b.col1 and a.col2=value) set state_a=state_b; --col1为b表的主键
括号里通过关联两表建立一个视图,set中设置好更新的字段。直观速度快,但b的主键一定要在where条件中,并且是以"="来关联被更新表,否则报错:ora-01779:无法修改与非键值保存表对应的列
merge into进行多表更新:merge table1 into table2 on condition when matched then update table1 set col1=value1,col2=value2 when not matched then insert (col_list) values (value_list);
快速游标更新法:
begin
for cr in (查询语句) loop --循环
--更新语句(根据查询出来的结果集合)
end loop;
end;
oracle支持快速游标,不需要定义直接把游标写到for循环中,方便批量更新数据。再加上rowid物理字段,可以快速定位到要更新的记录上。
方案 | 建议 |
标准update | 单表更新或较简单的语句采用使用此方案更优 |
inline view 更新法 | 两表关联且被更新表通过关联表主键关联的,此方案更优 |
meger into 更新法 | 两表关联且被更新表不是通过关联表主键关联的,此方案更优 |
快速游标更新法 | 多表关联且逻辑比较复杂的,此方案更优 |