2012-02-14 54 views
1

假设下面两个表格:甲骨文合并操作

users (username, region, location, department, subdepartment) 

structure (region, location, department, subdepartment) 

在启动,在用户表中,每个用户名出现在一个记录。如果用户名的子部门列为空,我希望能够自动分发到结构表中为该部门定义的所有子部门。

含义,而不是在用户表中只有一个记录,在结束将有N个记录,其中N表示在结构表中定义的原始区域,位置,部门组合子部门的数目。

我试着用MERGE语句来做这件事,但我无法弄清楚。我怎么能这样做? 谢谢!

+0

是否要插入用户或选择用户? – 2012-02-14 08:51:38

+0

我想插入用户 – maephisto 2012-02-14 09:02:37

回答

2

在速度,你可以这样做:

insert into users 
select 
    u.username, u.region, u.location, u.department, s.subdepartment 
from users u join structure s 
    on (u.region=s.region and u.location=s.location and u.department = s.department) 
where u.subdepartment is null; 

delete from users where subdepartment is null; 

但是,对于以上,则必须确保每个部门都分部门(如果不是的话,你必须做一些简单的PL/SQL)

0
create table table01 (
     code int, 
     name varchar(50), 
     old int 
); 

create table table02 (
     code int, 
     name varchar(50), 
     old int 
); 

insert into table01 values (1, 'A', 10); 
insert into table01 values (9, 'B', 12); 
insert into table01 values (3, 'C', 14); 
insert into table01 values (4, 'D', 16); 
insert into table01 values (5, 'E', 18); 

insert into table02 values (1, 'AA', null); 
insert into table02 values (2, 'BB', 123); 
insert into table02 values (3, 'CC', null); 
insert into table02 values (4, 'DD', null); 
insert into table02 values (5, 'EE', null); 

select * from table01 a order by 2; 
select * from table02 a order by 2; 

merge into table02 a using (
     select b.code, b.old from table01 b 
) c on (
    a.code = c.code 
) 
when matched then update set a.old = c.old 
;