我非常有用的声明我喜欢MySql是REPLACE INTO table
,它是'如果存在则替换值或者INSERT INTO表If-Not-Exist'。
db2 REPLACE
的文档仅适用于对字符串进行操作的函数,因此不适用于该含义。
db2中有没有等效的?现在我也在寻找关键字IF EXSTS/IF NOT EXIST
。
答案 0 :(得分:4)
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)
答案 1 :(得分:1)
您正在寻找的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将填补一些空白。