Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

H2 SQL database - INSERT if the record does not exist

Tags:

sql

h2

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 default values.

Something like this:

IF 'number of rows in ACCESSLEVELS' = 0
INSERT INTO ACCESSLEVELS VALUES
    (0, 'admin'),
    (1, 'SEO'),
    (2, 'sales director'),
    (3, 'manager'),
    (4, 'REP')
    ;
like image 951
szedjani Avatar asked Nov 04 '13 12:11

szedjani


People also ask

How do you insert if row does not exist in SQL?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.

Which command insert rows that do not exist and update the rows that exist?

Using REPLACE In the event that you wish to actually replace rows where INSERT commands would produce errors due to duplicate UNIQUE or PRIMARY KEY values as outlined above, one option is to opt for the REPLACE statement.

How do you find out if a record already exists in a database if it doesn't insert a new record?

You can either do this with a stored procedure or from ASP. SELECT 'This record already exists!' First, we check if the record exists with the EXISTS keyword. EXISTS executes the query we tell it to (the SELECT ) and returns a boolean value.

How do I add data to my H2 database?

Syntax. Following is the basic syntax of INSERT INTO statement. INSERT INTO tableName { [ ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) }


1 Answers

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.

If you do not name the columns, their values must be provided as defined in the table. If you prefer to name the columns to be more independent from their order in the table definition, or to avoid having to provide values for all columns when that is not necessary or possible:

MERGE INTO ACCESSLEVELS 
  (ID, LEVELNAME)
  KEY(ID) 
VALUES (0, 'admin'),
  (1, 'SEO'),
  (2, 'sales director'),
  (3, 'manager'),
  (4, 'REP');

Note that you must include the key column ("ID" in this example) in the column list as well as in the KEY clause.

like image 56
MartinB Avatar answered Sep 22 '22 07:09

MartinB