Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to avoid -803 in DB2 insert

Tags:

db2

I'm trying to insert a single row which may or may not already exist. I'd like to avoid selecting it first and/or getting a -803 if it does exist. I've done some research and tried both ignore and the merge statement, but keep getting syntax errors on both. In any case, I'm not trying copy the data from another table - so, merge is not really appropriate.
Isn't there some way in DB2 SQL to just issue a failure-proof insert and not have to code around this? In other words, is there some insert syntax which guarantees the data will be added if it doesn't exist or will return zero status even it it does?

like image 314
Mike GH Avatar asked Jan 13 '10 17:01

Mike GH


People also ask

How can I improve my insert performance?

To optimize insert speed, combine many small operations into a single large operation. Ideally, you make a single connection, send the data for many new rows at once, and delay all index updates and consistency checking until the very end.

Can I use select with insert?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

How do you insert an apostrophe in Db2?

Use two apostrophes '' to get a single apostrophe on DB2 too, according to the DB2 Survival Guide.


2 Answers

MERGE is appropriate, since you may dynamically supply values in the USING clause (see example 5 in http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm).

But MERGE is a DB2 V8.2 feature! You're probably on V8.1, aren't you?

If you implement the existence check like this:

SELECT
if (found) UPDATE else INSERT

beware of concurrency issues: Two concurrent threads may both find no column and then both try to insert, even if there's a transaction around the above code. To ensure this won't happen, you need to acquire an update lock with Repeatable Read in the above SELECT statement using WITH RR USE AND KEEP UPDATE LOCKS.

like image 128
Ralf Pantförder Avatar answered Sep 21 '22 22:09

Ralf Pantförder


In short, the answer is no. In long, it all depends on the constraints you have set up on your table. If you attempt to execute an insert against a table that has a unique constraint on a column, and the data already exists that you are trying to insert, you will get an error in DB2 (and any other RDBMS).

In this case, your best option is probably to write a stored procedure that checks to see if the record already exists before creating it.

like image 30
AJ. Avatar answered Sep 19 '22 22:09

AJ.