1

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

识别码 | PID | 价值1 | 价值2

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

识别码 | PID | 价值1

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

首先,将 STMT 中的 UID 和 PID 对与表 1 中的进行比较,

  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,否则什么也不做。

我无法为条件 2 提出解决方案。感谢您的帮助!

4

2 回答 2

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
于 2012-06-04T17:19:34.163 回答
0


您可以使用以下查询

MERGE INTO TABLE1 T
USING STMT S
ON (T.UID  = S.UID AND T.PID = S.PID)
WHEN MATCHED THEN
UPDATE
SET
T.VALUE1 = CASE WHEN T.VALUE2 > 0 OR (T.VALUE2 = 0 AND T.VALUE1 <> S.VALUE1) THEN S.VALUE1 END
WHEN NOT MATCHED THEN
INSERT INTO T (COLUMNS) (SELECT COLUMNS FROM S);
于 2017-05-11T14:43:19.323 回答