2012-02-14 7 views
1

はのは、次の2つのテーブルを想定してみましょう:のOracleマージ操作

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

structure (region, location, department, subdepartment) 

は開始時に、ユーザーテーブルに、各ユーザ名は一つのレコードに表示されます。ユーザー名にサブディメンション列が空の場合、構造テーブルのその部門に定義されたすべてのサブディビジョンに自動的に配布されるようにしたいと思います。

意味は、usersテーブルのレコードが1つではなく、N個のレコードが存在することを意味します.Nは、元の地域、場所、部署の組み合わせの構造テーブルで定義されたサブディレクトリの数を表します。

私はMERGEステートメントでこれを実行しようとしましたが、わかりません。どうすればこのことができますか? ありがとうございました!

+0

ユーザーを挿入するか、ユーザーを選択しますか? –

+0

私はユーザーを挿入したい – maephisto

答えて

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 
; 
関連する問題