【转载】oracle更新语法

oracle更新语法:
1.一般语法
   update tab set col = .... [where ...]   =后可以有子查询,但是必须对于tab的每一列返回唯一一行与之对应,where是需要更新的表,部分更新必须加,否则相关子查询的更新会把没有匹配的更新为null,如
  update tab a set a.col=(select b.col from b where a.id=b.id) where exists (select 1 from b where a.id=b.id) 类似地写了多遍

2.改进语法merge
  merge into tab
  using (表|视图|子查询等)  --子查询需要加括号  on (条件)
  when match then
   do update
  when no match then
  do insert                               

insert语法和update语法有所不同,详细参考文档,10g还支持update,insert的有条件更新和插入,支持update的delete where,支持只有update或insert的
不能修改using里的关联列,同样,必须每一行有唯一与之对应的

上面两种语法如果找不到唯一对应的,需要改进语句,比如加rownum=1

3.update inline view的用法
   update (select ...........关联查询) set 目标=源
  如 update(select a.name,b.name from a,b where a.id=b.id) set a.name=b.name;
      需要unique建保证唯一对应,比如上面的必须要b.id有唯一键,也就是preserved key,比如唯一索引什么的都可以,11g之前可以用hint: bypass_ujvc,这样不需要唯一键,但是可能有问题,一对多会更新多次,11g这个hint失效
  delete (select ....) 也可以,有很多要求,可以看sql文档,insert (select ...)限制更多
  第3种方法来源于可更新的视图


oracle更新基本有3种sql写法,后面两种往往优化中会使用到,特别第一种的更新关联子查询中源表不走索引,那么更新很多,相当于 nested loop,肯定慢,而且还有个where过滤,多次访问源表

posted @ 2017-06-30 13:46  魔豆  阅读(521)  评论(0编辑  收藏  举报