Search code examples
jdbcinserthsqldb

hsqldb update on insert


Does anyone know of a solution to make HSQLDB update columns by calling INSERT. I would like my code to be able to insert, and if there's already data, to update that data. I know MySQl, I believe, has 'ON DUPLICATE KEY UPDATE'. I can't seem to find any recent documentation on this.


Solution

  • A good sample is sometimes better the formal documentation on MERGE statement :)

    Sample 1

    For a table (MY_TABLE) with tho columns (COL_A and COL_B), where the first column is a primary key:

    MERGE INTO MY_TABLE AS t USING (VALUES(?,?)) AS vals(a,b) 
            ON t.COL_A=vals.a
        WHEN MATCHED THEN UPDATE SET t.COL_B=vals.b
        WHEN NOT MATCHED THEN INSERT VALUES vals.a, vals.b
    

    Sample 2

    Let's add another column (COL_C) to our table:

    MERGE INTO MY_TABLE AS t USING (VALUES(?,?,?)) AS vals(a,b,c) 
            ON t.COL_A=vals.a
        WHEN MATCHED THEN UPDATE SET t.COL_B=vals.b, t.COL_C=vals.c
        WHEN NOT MATCHED THEN INSERT VALUES vals.a, vals.b, vals.c
    

    Sample 3

    Now let's change the primary key to consist of first two columns (COL_A and COL_B):

    MERGE INTO MY_TABLE AS t USING (VALUES(?,?,?)) AS vals(a,b,c) 
            ON t.COL_A=vals.a AND t.COL_B=vals.b
        WHEN MATCHED THEN UPDATE SET t.COL_C=vals.c
        WHEN NOT MATCHED THEN INSERT VALUES vals.a, vals.b, vals.c
    

    Enjoy!