转 update关联更新在sqlserver和oracle中的实现

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: 无法修改与非键值保存表对应的列
被修改的表则无需增加主键

posted on   荣锋亮  阅读(836)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示