【问题标题】:Oracle merge operationoracle合并操作
【发布时间】:2012-03-05 15:26:56
【问题描述】:

让我们假设接下来的两个表:

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

structure (region, location, department, subdepartment)

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

意思是,users表中不是只有一条记录,最后会有N条记录,其中N表示结构表中为原始区域、位置、部门组合定义的子部门的数量。

我试过用 MERGE 语句来做这件事,但我想不通。我怎么能这样做? 谢谢!

【问题讨论】:

  • 是插入用户还是选择用户?

标签: c# sql oracle merge


【解决方案1】:
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
;

【讨论】:

    【解决方案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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2011-09-10
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 2016-04-14
      相关资源
      最近更新 更多