---
title: "oracle中你不常用的update语句"
author: "Eric.Yan"
date: "2012-04-10T17:39:57Z"
tags: ["Oracle", "Update", "exists", "类视图"]
categories: ["数据库"]
slug: "oracle-update"
draft: false
lastmod: "2012-04-10T17:39:57Z"
id: 1482011
url: "https://eric-yan.iteye.com/blog/1482011"
---

题记：oracle中并没有update  from的语句。

 

这里重点介绍基于另外的表更新当前表的操作。

比如你有一张user表，是参考user\_ref得来的，换句话说，你user表的用户都来自user\_ref，但是中途出现一些问题，user表中的有些user的first\_name, last\_name不对，现在要求用user\_ref的相对应的name来更新user表：

首先，对user表做个copy,确定数据没错后再对真正的user表操作

 

create table myuser as select * from rp\_user;

 

方案一：

 

我们可以这么写

 

update myuser  
set(first\_name, last\_name) =  
(  
  select rpref.first\_name first\_name, rpref.last\_name last\_name  
  from rp\_ref\_employee rpref  
  where rpref.soe\_id(+) = myuser.sso\_id  
  and rpref.soe\_id is not null  
)  
where exists  
(  
  select 1 from rp\_ref\_employee rpref where rpref.soe\_id(+) = myuser.sso\_id and rpref.soe\_id is not null  
);

 

请你尤其注意这里的where子句，如果你不写，oracle将默认更新所有的值，如果某些值在子查询中找不到，将会使得myuser中出现很多空值；

 

方案二：

 

update  
(  
  select myuser.first\_name myfn, rpref.first\_name rpfn, myuser.last\_name myln, rpref.last\_name rpln  
  from myuser, rp\_ref\_employee rpref  
  where rpref.soe\_id(+) = myuser.sso\_id  
  and rpref.soe\_id is not null  
)  
set myfn = rpfn, myln = rpln;

 

这里的表是一个类视图，你执行的时候可能会遇到这样的错误，‘无法修改与非键值保存表对应的列’，这是因为新建表还没有主键　的缘故，新建主键；

 

 

summary:

 

在oracle中不存在update from结构，如果遇到需要从另外一个表来更新本表值的时候，有２种方案，一种是使用子查询，此时一定要注意where 条件（一般后面接exists），除非两个表是一一对应的，否则where条件不可少；

还有就是类视图的更新方法，这也是oracle所独有的！

 

reference: [http://wenku.baidu.com/view/7db8c0d4b14e852458fb576e.html](http://wenku.baidu.com/view/7db8c0d4b14e852458fb576e.html)

 

                 [http://wenku.baidu.com/view/4f497c5277232f60ddcca121.html](http://wenku.baidu.com/view/4f497c5277232f60ddcca121.html)