H2数据库更新行或如​​果不存在则插入-合并语法错误

时间:2019-06-16 11:37:50

标签: merge sql-update h2 sql-insert insert-update

我想在具有MERGE INTO函数的H2数据库表上执行“更新行”或“如果不存在则插入”语句。

塔贝尔像:

CREATE TABLE TARGET_TABLE
( cola VARCHAR(10),
colb VARCHAR(10), 
colc VARCHAR(10), 
col1 INT, 
colz VARCHAR(10) 
);

要合并的关键字段是:“ cola”和“ colb”。

我尝试了以下操作:

MERGE INTO TARGET_TABLE USING DUAL
         ON cola = 'a' AND colb = 'b' 
        WHEN NOT MATCHED THEN 
             INSERT VALUES ('a', 'b', 'cc', 1, 'zz')
        WHEN MATCHED THEN UPDATE SET colc = 'cc', col1 = TARGET_TABLE.col1 + 1  --Aggregation
        colz = CASEWHEN(TARGET_TABLE.colz IS NULL, 'zz', TARGET_TABLE.colz ); --check if it is null

错误: [42001] [42001] SQL语句“ MERGE INTO TARGET_TABLE USING [*] DUAL

”中的语法错误

第二次尝试:

MERGE INTO TARGET_TABLE AS T
     (SELECT 'a' cola, 'b' colb, 'cc' colc, 1 col1, 'zz' colz FROM DUAL) as D
    ON (T.cola = D.cola AND
        T.colb = D.colb 
    )
    WHEN MATCHED THEN UPDATE 
        T.colc = D.colc,
        T.col1 = T.col1 + D.col1
        T.colz = CASEWHEN(T.colz IS NULL, D.colz, T.colz );
    WHEN NOT MATCHED THEN
        INSERT VALUES (D.cola, D.colb, D.colc, D.col1, D.colz);

错误: SQL语句“ MERGE INTO TARGET_TABLE AS T [*]

中的语法错误

第三次尝试:

MERGE INTO TARGET_TABLE KEY(cola,colb) VALUES( 'a', 'b', 'cc', 1, 'zz')
    WHEN MATCHED THEN UPDATE
        colc = 'cc',
        col1 = TARGET_TABLE.e + 1
        colz = CASEWHEN(TARGET_TABLE.z IS NULL, 'zz', ARGET_TABLE.z );
    WHEN NOT MATCHED THEN
        INSERT VALUES ('a', 'b', 'cc', 1, 'zz');

错误: [42000] [42000] SQL语句“ [[]]匹配然后合并到TARGET_TABLE KEY(cola,colb)VALUES('a','b','cc',1,'zz')中的语法错误”;

所以我想在表中得到以下结果:

如果行尚不存在:

['a', 'b', 'cc', 1, 'zz']

如果它已经存在,请更新一些字段

['a', 'b', 'cc', old_value+1, 'z']

['a', 'b', 'cc', old_value+1, 'zz']

取决于colz的值是否为NULL。

0 个答案:

没有答案