H2 SQL database - INSERT if the record does not exist

后端 未结 4 1176
名媛妹妹
名媛妹妹 2020-12-19 04:29

I would like initialize a H2 database, but I am not sure if the records exist. If they exist I don\'t want to do anything, but if they don\'t exist I would like to write the

4条回答
  •  遥遥无期
    2020-12-19 05:01

    Here is another way:

    CREATE TABLE target (C1 VARCHAR(255), C2 VARCHAR(255));
    
    MERGE INTO target AS T USING (SELECT 'foo' C1, 'bar') AS S ON T.C1=S.C1
    WHEN NOT MATCHED THEN
        INSERT VALUES('foo', 'bar')
    

    When a row in S matches one or more rows in T, do nothing. But when a row in S is not matched, insert it. See "MERGE USING" for more details:

    https://www.h2database.com/html/commands.html#merge_using

提交回复
热议问题