MySql REPLACE INTO的db2等效项

vlju58qv  于 2023-01-12  发布在  Mysql
关注(0)|答案(2)|浏览(122)

我非常有用的声明,我喜欢的MySql是REPLACE INTO table,这是'替换一个值,如果存在或插入到表,如果不存在'。
db2 REPLACE的文档是针对一个只对字符串进行操作的函数的,所以没有这个含义。
在db2中是否有任何等价物?现在我也在寻找关键字IF EXSTS/IF NOT EXIST

3htmauhk

3htmauhk1#

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)
z8dt9xmd

z8dt9xmd2#

您要查找的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的这个explanation将填补一些空白。

相关问题