2011-12-07 47 views
4

我是新來的Oracle SQL所以我有一個問題..我有兩個表,表A和表B ..現在表A和表B有相同的列名,但在表A中,只有一列(名爲「跟蹤」)實際上在它的數據。在表A列的其餘部分是空的......我需要做的就是更新表A中的每個記錄,這樣對於其他列值從表B複製什麼,其條件是從表A中的「跟蹤」的列值與在表B中的「跟蹤」列匹配..怎麼辦我用一個條件子句更新現有記錄?

任何想法?

回答

2
MERGE INTO tableA a 
USING tableB b 
ON (a.tracker=b.tracker) 
WHEN MATCHED THEN UPDATE SET 
    a.column1=b.column1, 
    a.column2=b.column2; 

如果存在B中的行並不在一個存在:

MERGE INTO tableA a 
USING tableB b 
ON (a.tracker=b.tracker) 
WHEN MATCHED THEN UPDATE SET 
    a.column1=b.column1, 
    a.column2=b.column2 
WHEN NOT MATCHED THEN INSERT VALUES 
    a.tracker,a.column1,a.column2; --all columns 
2
create table a (somedata varchar2(50), tracker number , constraint pk_a primary key (tracker)); 
create table b (somedata varchar2(50), tracker number, constraint pk_b primary key (tracker)); 
/

--insert some data 
insert into a (somedata, tracker) 
select 'data-a-' || level, level 
    from dual 
    connect by level < 10; 

insert into b (somedata, tracker) 
    select 'data-b-' || -level, level 
    from dual 
    connect by level < 10; 



    select * from a; 
SOMEDATA           TRACKER 
-------------------------------------------------- ------- 
data-a-1             1 
data-a-2             2 
data-a-3             3 
data-a-4             4 
data-a-5             5 
data-a-6             6 
data-a-7             7 
data-a-8             8 
data-a-9             9 

    select * from b; 
    SOMEDATA           TRACKER 
-------------------------------------------------- ------- 
data-b--1            1 
data-b--2            2 
data-b--3            3 
data-b--4            4 
data-b--5            5 
data-b--6            6 
data-b--7            7 
data-b--8            8 
data-b--9            9 

    commit; 


    update (select a.somedata a_somedata, b.somedata b_somedata 
      from a 
        inner join 
        b 
        on a.tracker = b.tracker) 
    set 
      a_somedata = b_somedata; 


select * from a;   --see below for results-- 

     --or you can do it this way: (issuing rollback to get data back in previous state) 
     --for a one column update, either way will work, I would prefer the former in case there is a multi-column update necessary 
     -- merge *as posted by another person* will also work 

     update a 
      set somedata = (select somedata 
          from b 
          where a.tracker = b.tracker 
          ); 

      select * from A; --see below for results-- 

      -- clean up 
      -- drop table a; 
      -- drop table b; 

這會給你的結果:

SOMEDATA           TRACKER 
-------------------------------------------------- ------- 
data-b--1            1 
data-b--2            2 
data-b--3            3 
data-b--4            4 
data-b--5            5 
data-b--6            6 
data-b--7            7 
data-b--8            8 
data-b--9            9 

這裏是甲骨文的一個鏈接在UPDATE

文檔