2014-09-03 68 views
0

我在同步兩個表時遇到問題。所以我有這2個表,同步兩個表,更新值並插入不存在的行

表TESTA

NAME VALUE1 VALUE2 VALUE3 SOURCEVAL RESULT 
HEAD1  1  0  0  50 100 
HEAD2  0  1  0  50  50 
HEAD3  0  0  1  50 200 

表TESTB

NAME  V1  V2  V3 SOURCEVAL RESULT 
HEAD1  10  99  99  99  99 
HEAD5  99  99  99  99  99 
HEAD6  20  99  99  99  99 

什麼我的目標做的是在TESTB, 同步這兩個表,並將其儲存所需結果是這樣的,

TABLE TESTB

NAME  V1  V2  V3 SOURCEVAL RESULT 
HEAD1  1  0  0  50 100 
HEAD2  0  1  0  50  50 
HEAD3  0  0  1  50 200 
HEAD5  99  99  99  99  99 
HEAD6  20  99  99  99  99 

我的SQL是這樣的,

UPDATE t2 SET t2.v1 = t1.value1 and t2.v2 = t1.value2 and t2.v3 = t1.value3 and t2.sourceval = t1.sourceval and t2.result = t1.result FROM testb AS t2 INNER JOIN testa AS t1 ON t2.name = t1.name 

我在做什麼錯在這裏?有人可以建議我一個更好的解決方案?

+2

閱讀有關'merge'運營商在Oracle – 2014-09-03 07:17:11

回答

1

使用MERGE

MERGE語句

MERGE INTO TESTB trg 
    USING TESTA src 
     ON (trg.CNAME = src.CNAME) 
WHEN MATCHED 
THEN 
    UPDATE SET trg.V1 = src.VALUE1, 
       trg.V2 = src.VALUE2, 
       trg.V3 = src.VALUE3, 
       trg.SOURCEVAL = src.SOURCEVAL, 
       trg.RESULT = src.RESULT 
WHEN NOT MATCHED 
THEN 
    INSERT  (trg.CNAME, 
       trg.V1, 
       trg.V2, 
       trg.V3, 
       trg.SOURCEVAL, 
       trg.RESULT) 
     VALUES (src.CNAME, 
       src.VALUE1, 
       src.VALUE2, 
       src.VALUE3, 
       src.SOURCEVAL, 
       src.RESULT); 

SQLFiddle Demo

CREATE TABLE TESTA 
(
    CNAME  VARCHAR2 (16), 
    VALUE1  NUMBER, 
    VALUE2  NUMBER, 
    VALUE3  NUMBER, 
    SOURCEVAL NUMBER, 
    RESULT  NUMBER 
); 


CREATE TABLE TESTB 
(
    CNAME  VARCHAR2 (16), 
    V1   NUMBER, 
    V2   NUMBER, 
    V3   NUMBER, 
    SOURCEVAL NUMBER, 
    RESULT  NUMBER 
); 

INSERT INTO TESTA (CNAME, 
        VALUE1, 
        VALUE2, 
        VALUE3, 
        SOURCEVAL, 
        RESULT) 
    VALUES ('HEAD1', 
      1, 
      0, 
      0, 
      50, 
      100); 
INSERT INTO TESTA (CNAME, 
        VALUE1, 
        VALUE2, 
        VALUE3, 
        SOURCEVAL, 
        RESULT) 
    VALUES ('HEAD2', 
      0, 
      1, 
      0, 
      50, 
      50); 
INSERT INTO TESTA (CNAME, 
        VALUE1, 
        VALUE2, 
        VALUE3, 
        SOURCEVAL, 
        RESULT) 
    VALUES ('HEAD3', 
      0, 
      0, 
      1, 
      50, 
      200); 
INSERT INTO TESTB (CNAME, 
        V1, 
        V2, 
        V3, 
        SOURCEVAL, 
        RESULT) 
    VALUES ('HEAD5', 
      99, 
      99, 
      99, 
      99, 
      99);  
INSERT INTO TESTB (CNAME, 
        V1, 
        V2, 
        V3, 
        SOURCEVAL, 
        RESULT) 
    VALUES ('HEAD6', 
      20, 
      99, 
      99, 
      99, 
      99); 
+0

超級真棒感謝試試下面的辦法! – marmar 2014-09-04 03:58:22

相關問題