H2 SQL database - INSERT if the record does not exist

后端 未结 4 1160
名媛妹妹
名媛妹妹 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 04:59

    To do this you can use MySQL Compatibility Mode in H2 database. Starting from 1.4.197 version it supports the following syntax: INSERT IGNORE INTO table_name VALUES ...

    From this pull request:

    INSERT IGNORE is not supported in Regular mode, you have to enable MySQL compatibility mode explicitly by appending ;MODE=MySQL to your database URL or by executing SET MODE MySQL statement.

    From official site:

    INSERT IGNORE is partially supported and may be used to skip rows with duplicate keys if ON DUPLICATE KEY UPDATE is not specified.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-19 05:07

    The following works for MySQL, PostgreSQL, and the H2 database:

    drop table ACCESSLEVELS;
    
    create table ACCESSLEVELS(id int, name varchar(255));
    
    insert into ACCESSLEVELS select * from (
    select 0, 'admin' union
    select 1, 'SEO' union
    select 2, 'sales director' union
    select 3, 'manager' union
    select 4, 'REP'
    ) x where not exists(select * from ACCESSLEVELS);
    
    0 讨论(0)
  • 2020-12-19 05:09
    MERGE INTO ACCESSLEVELS 
      KEY(ID) 
    VALUES (0, 'admin'),
      (1, 'SEO'),
      (2, 'sales director'),
      (3, 'manager'),
      (4, 'REP');
    

    Updates existing rows, and insert rows that don't exist. If no key column is specified, the primary key columns are used to find the row.

    0 讨论(0)
提交回复
热议问题