海上月明

editer by sun
posts - 162, comments - 51, trackbacks - 0, articles - 8
   :: 首页 :: 新随笔 ::  :: 聚合  :: 管理

from:http://www.blogjava.net/pts/archive/2010/11/23/338825.html

sqlserver和oracle中实现update关联更新的语法不同,都可以通过inline view(内嵌视图)
来实现,总的来说sqlserver更简单些. 测试例子如下:


create table tmp_a
(cpcode varchar2(10),
sb_ym varchar2(6),
flag char(1)
);

create table tmp_b
(cpcode varchar2(10),
sb_ym varchar2(6),
flag char(1)
);

insert into tmp_a(cpcode,sb_ym,flag)values('3201910001','200406','e');
insert into tmp_a(cpcode,sb_ym,flag)values('3201910002','200406','e');
insert into tmp_b(cpcode,sb_ym,flag)values('3201910001','200406','r');
insert into tmp_b(cpcode,sb_ym,flag)values('3201910002','200406','r');
insert into tmp_b(cpcode,sb_ym,flag)values('3201910003','200406','r');
insert into tmp_b(cpcode,sb_ym,flag)values('3201910004','200406','e');
commit;

在SQLSERVER中:

update tmp_b set flag = b.flang from tmp_a a,tmp_b b 
where a.cpcode =b.cpcode and a.sb_ym = b.sb_ym;


在Oracle中:

方法一:(效率低)
update tmp_b a
set flag = (select flag from tmp_a b
where a.cpcode = b.cpcode and a.sb_ym = b.sb_ym ) 
where exists 
(select * from tmp_a c 
where a.cpcode = c.cpcode and a.sb_ym = c.sb_ym);

Statistics
----------------------------------------------------------
8 recursive calls
3 db block gets
18 consistent gets
0 physical reads
0 redo size

方法二:(效率高)
alter table tmp_a add constraint p_tmp_a primary key (cpcode, sb_ym);

update (select b.flag flagb,a.flag flaga 
from tmp_a a,tmp_b b 
where a.cpcode=b.cpcode 
and a.sb_ym=b.sb_ym) 
set flagb=flaga;

Statistics
----------------------------------------------------------
0 recursive calls
3 db block gets
7 consistent gets
0 physical reads
0 redo size


注意:方法二中数据源表必须要加上主键,否则会报错 
ORA-01779: 无法修改与非键值保存表对应的列
被修改的表则无需增加主键


只有注册用户登录后才能发表评论。


网站导航: