我非常喜欢MySql中的一个实用语句REPLACE INTO table
,它的含义是'如果存在则替换该值,如果不存在则插入到表格中'。
db2文档中的REPLACE
函数仅适用于操作字符串,因此不具有相同的含义。
在db2中是否有相当的语句?目前我也在寻找关键字IF EXSTS/IF NOT EXIST
。
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)
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的解释将填补一些空白。