From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.
My code now does a select
and if no result is returned it does an insert
. I really don't like this code since it exposes me to concurrency issues when running in a multi-threaded environment.
What I would like to do is to put this logic in DB2 instead of in my Java code.
Does DB2 have an insert-or-update
statement? Or anything like it that I can use?
For example:
insertupdate into mytable values ('myid')
Another way of doing it would probably be to always do the insert and catch "SQL-code -803 primary key already exists", but I would like to avoid that if possible.
Yes, DB2 has the MERGE statement, which will do an UPSERT (update or insert).
See:
http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm
This response is to hopefully fully answer the query MrSimpleMind had in use-update-and-insert-in-same-query and to provide a working simple example of the DB2 MERGE statement with a scenario of inserting AND updating in one go (record with ID 2 is updated and record ID 3 inserted).
Another way is to execute this 2 queries. It's simpler than create a MERGE statement:
The first query just updateS the field you need, if the MyId exists. The second insertS the row into db if MyId does not exist.
The result is that only one of the queries is executed in your db.
I found this thread because I really needed a one-liner for DB2 INSERT OR UPDATE.
The following syntax seems to work, without requiring a separate temp table.
It works by using VALUES() to create a table structure . The SELECT * seems surplus IMHO but without it I get syntax errors.
if you have to insert more than one row, the VALUES part can be repeated without having to duplicate the rest.
The result is a single statement that can INSERT OR UPDATE one or many rows presumably as an atomic operation.