根据另一个表中的值更新表

时间:2014-10-23 03:44:59

标签: sql oracle sql-update

所以我有这两个表:

TEST_TABLE_A
------- ------ ------ --------    
 NAME    VAL1   VAL2   STATUS
------- ------ ------ --------
 HEAD1   100    200    ACTIVE
 HEAD2   300    400    ACTIVE
 HEAD3   500    600    ACTIVE
 HEAD4   700    800    ACTIVE


TEST_TABLE_B
------- ------ ------    
 NAME    VAL1   VAL2
------- ------ ------
 HEAD1   1      2
 HEAD2   3      4
 HEAD3   500    600

我想基于表b同步表a,表a中所需的站点应该是这样的

 NAME    VAL1   VAL2   STATUS
------- ------ ------ ----------
 HEAD1   100    200    INACTIVE
 HEAD1     1      2      ACTIVE
 HEAD2   300    400    INACTIVE
 HEAD2     3      4      ACTIVE
 HEAD3   500    600      ACTIVE
 HEAD4   700    800      ACTIVE

我不知道如何使用我的查询来帮助我:

INSERT INTO TEST_TABLE_A (NAME,VAL1,VAL2,STATUS)
SELECT NAME, VAL1, VAL2, 'ACTIVE' FROM TEST_TABLE_B
Where TEST_TABLE_A.NAME = TEST_TABLE_B.NAME
  AND TEST_TABLE_A.VAL1 != TEST_TABLE_B.VAL1
  AND TEST_TABLE_A.VAL2 != TEST_TABLE_B.VAL2
  AND TEST_TABLE_A.STATUS = 'ACTIVE';

UPDATE TEST_TABLE_A SET STATUS = 'INACTIVE'
Where TEST_TABLE_A.NAME = TEST_TABLE_B.NAME
  AND TEST_TABLE_A.VAL1 != TEST_TABLE_B.VAL1
  AND TEST_TABLE_A.VAL2 != TEST_TABLE_B.VAL2
  AND TEST_TABLE_A.STATUS = 'ACTIVE';

1 个答案:

答案 0 :(得分:0)

SQL FIDDLE

当名称匹配但值不匹配时,首次更新状态为非活动状态 插入新条目,我正在使用MERGE。

UPDATE TEST_TABLE_A A
SET A.STATUS ='INACTIVE'
WHERE EXISTS
(
    SELECT 1 FROM TEST_TABLE_B B
    WHERE B."NAME" = A."NAME"
      AND B."VAL1" != A."VAL1" AND B."VAL2" != A."VAL2"
);

MERGE INTO TEST_TABLE_A D
USING ( SELECT * FROM TEST_TABLE_B) S
ON ( D."NAME" = S."NAME" AND D."VAL1" = S."VAL1" AND D."VAL2"= S."VAL2")
WHEN NOT MATCHED THEN
INSERT (D."NAME", D."VAL1",D."VAL2", D."STATUS")
values (S."NAME", S."VAL1",S."VAL2", 'ACTIVE');