求oracle SQL修改多行记录解决方法

求oracle SQL修改多行记录请问怎么用一个SQL修改多行记录。现在有2张表,gap_organize,gap_user. gap_user有

求oracle SQL修改多行记录
请问怎么用一个SQL修改多行记录。

现在有2张表,gap_organize,gap_user. gap_user有Code,belong_org列,gap_organize表里面有ID,Code.现在里面有6000条数据。

做的目的是 修改gap_user表里面的belong_org值,具体的值是gap_organize里面的id, 条件是 gap_user里面Code的前6位 和gap_organize表里的Code相等.

参照原来提问的,我的写法在下图 原来的可以,现在的怎么不行报错“单行子查询返回多行”。
原来的地址:http://topic.csdn.net/u/20121015/14/a66981be-097d-4349-8c76-de1711ccc1c4.html

操作见下面图片。


[最优解释]
报错“单行子查询返回多行”是因为对于某个gap_user.code的前6位,在gap_organize 中有多个记录。
你可以查询下看看那些code对应多条记录。
select code, count(*) from gap_organize group by code having count(*) > 1;

如果多条记录里面随便取条,可以改成
update gap_user
  set belong_org = max(select org.id
  from gap_organize org, gap_user u
  where length(u.code) > 8
  and org.code = substr(u.code, 0, 6));


[其他解释]

引用:
嗯 我去试试。

看你上次回答,挺好。后来其他地方的数据,导入到表里, 我再次执行怎么报错,
ORA-01407: 无法更新 ("HBACCOUNT"."GAP_ELE_AGENCY"."ID") 为 NULL


--预算单位脚本
update gap_ele_agency set ID=(
select ID from gap_organize where ORG_TYPE_……


查询有没有为NUll的id,这个报错是因为select ID from gap_organize where ORG_TYPE_ID=2 and code=gap_ele_agency.code这个查不到数据,和gap_organize表本身没关系。

可以试试用NVL(MAX(go.ID),gea.ID)包装一下。
[其他解释]
我的写法;

--查询 
select belong_org from gap_user where code = '011001001'; --为4440

--1 拿011001001举例,gap_user表里面的code列的一个值

--2 取当code的前6位 比如011001001的前6位 011001

select id from gap_organize where code = 011001;

--3取出结果id设置为gap_user表的 belong_org

update gap_user
   set belong_org = (select id from gap_organize where code = '011001')
 where code = '011001001';

--查询 
select belong_org from gap_user where code = '011001001'; --为2644 

--说明以上单个修改没有问题 现在需要批量的修改 

update gap_user
   set belong_org = (select org.id
                       from gap_organize org, gap_user u
                      where length(u.code) > 8
                        and org.code = substr(u.code, 0, 6));

update gap_user
   set belong_org = (select id
                       from gap_organize
                      where length(gap_user.code) > 8
                        and code = substr(gap_user.code, 0, 6));



select org.id
  from gap_organize org, gap_user u
 where length(u.code) > 8
   and org.code = substr(u.code, 0, 6);


[其他解释]
嗯 我去试试。

看你上次回答,挺好。后来其他地方的数据,导入到表里, 我再次执行怎么报错,
ORA-01407: 无法更新 ("HBACCOUNT"."GAP_ELE_AGENCY"."ID") 为 NULL


--预算单位脚本
update gap_ele_agency set ID=(
select ID from gap_organize where ORG_TYPE_ID=2 and code=gap_ele_agency.code);

我也查询,了看看有没有为NUll的id,结果 都没有。

select * from gap_ele_agency where id=null;
select * from gap_organize where id=null;
[其他解释]
确实 是这个问题。select ID from gap_organize where ORG_TYPE_ID=2 and code=gap_ele_agency.code


我想问下 
update gap_ele_agency set ID=(
select ID from gap_organize where ORG_TYPE_ID=2 and code=gap_ele_agency.code);
这里面gap_organize的条数必须大于等于gap_ele_agency 条数吗?

比如 两个表都 code 为 001,001001,001002,但是gap_organize 里面001的 TYPE_ID=3, 

我把条件给删除了,就好了 select ID from gap_organize where code=gap_ele_agency.code

[其他解释]
如果你用NVL封过就可以忽略条数,因为即使没有也不会更新。