Oracle SQL:根据与SQL语句的比较有条件地更新表

时间:2012-06-04 17:09:37

标签: sql oracle

我有一个表(TABLE1),它有4列:

UID | PID | VALUE1 | VALUE2

我有另一个SQL语句(STMT)从一些其他表返回3列:

UID | PID | VALUE1

现在这里是我想要更新TABLE1的条件:

首先,将STMT中的UID和PID对与TABLE1中的那些对比,

  1. 对于不在TABLE1中的所有新UID和PID对,将新行从STMT插入到TABLE1中,设置TABLE1.VALUE2 = 0(我已经完成了这一行)

  2. 对于STMT和TABLE1中的现有UID和PID对,执行:

    一个。如果TABLE1.VALUE2> 0,更新TABLE1.VALUE1 = STMT.VALUE1

    湾如果TABLE1.VALUE2 = 0并且如果TABLE1.VALUE1!= STMT.VALUE1,则更新TABLE1.VALUE1 = STMT.VALUE1,否则不执行任何操作。

  3. 我无法提出条件2的解决方案。感谢所有帮助!

1 个答案:

答案 0 :(得分:2)

UPDATE (
    SELECT table1.UID
           ,table1.PID
           ,table1.value1 AS table1_value1
           ,table1.value2 AS table1_value2
           ,stmt.value1 AS stmt_value1
    FROM table1
    INNER JOIN (SELECT ? AS UID
                       ,? AS PID
                       ,? AS value1
                FROM whatever) stmt
        ON stmt.UID = table1.UID
        AND stmt.PID = table1.PID
) x
SET x.table1_VALUE1 = CASE WHEN (x.table1_VALUE2 > 0) OR
                              (x.table1_VALUE2 = 0 AND x.table1_VALUE1 <> x.stmt_VALUE1)
                              THEN x.stmt_VALUE1
                         ELSE x.table1_VALUE1 
                    END