3

我喜欢MySql的非常有用的语句REPLACE INTO table是'REPLACE a value if-exist OR INSERT INTO table If-Not-Exist'。

db2 的文档 REPLACE是针对仅对字符串进行操作的函数,因此没有这个含义。

db2中是否有任何等价物?现在我也在寻找关键字IF EXSTS/IF NOT EXIST

4

2 回答 2

5

DB2 使用 SQL 标准MERGE语句来做基本相同的事情。语法不同:

MERGE INTO table_to_upsert AS tab
USING (VALUES
        (1, 2, 3),
        (4, 5, 6),
        (7, 8, 9)
        -- more rows
    ) AS merge (C1, C2, C3)
    ON tab.key_to_match = merge.key_to_match
    WHEN MATCHED THEN
        UPDATE SET tab.C1 = merge.C1,
                   tab.C2 = merge.C2,
                   tab.C3 = merge.C3
    WHEN NOT MATCHED THEN
        INSERT (C1, C2, C3)
        VALUES (merge.C1, merge.C2, merge.C3)
于 2013-03-29T13:35:21.900 回答
2

您正在寻找的 DB2 函数是 MERGE

CREATE TABLE FOO ( ID INT, TITLE VARCHAR(500), VALUE );
CREATE TABLE BAR ( ID INT, TITLE VARCHAR(500), VALUE );
INSERT INTO FOO VALUES (1, 'BAR', 5.0);
INSERT INTO BAR VALUES (1, 'CCC', 3.0);
INSERT INTO BAR VALUES (2, 'DDD', 1.0);

MERGE INTO FOO AS F
   USING BAR AS B
   ON (F.ID = B.ID) WHEN MATCHED THEN UPDATE SET TITLE = B.TITLE, VALUE = F.VALUE - B.VALUE
   WHEN NOT MATCHED THEN INSERT VALUES(B.ID, B.TITLE, B.VALUE);

SELECT ID, TITLE, VALUE FROM FOO;
1    CCC    2.0
2    DDD    1.0

DeveloperWorks 的这一解释将填补一些空白。

于 2013-03-29T13:37:26.493 回答