Ghassen
Ghassen

Reputation: 781

Db2: How to insert new and update existing data?

I am using the IBM Db2 database system. I have a table with 3 columns (1 primary key and others) that I fill after reading from a CSV file. It happens that sometimes I get a repeated data from my file so in this case I need to ignore it.

My problem here is that I can't found the correct Db2 SQL statement that will do Insert Or Update. With my current solution I get an exception in my code:

DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=1;DB2INST1.TI_APGROUP_0, DRIVER=4.12.55

Is there a simple way to INSERT or UPDATE?

Upvotes: 0

Views: 5462

Answers (2)

Ghassen
Ghassen

Reputation: 781

I found a solution that does what I want but I don't know if it's the best way or not ! Anyway I post it to help who's facing the same problem but if anyone's have another suggestion it's welcome :

MERGE INTO KDDBD01.KDTCTCT AS CT USING (SELECT COUNT(ADR_MAIL_UTIL) FROM KDDBD01.KDTCTCT) ON (CT.ADR_MAIL_UTIL = :contactEmail) WHEN NOT MATCHED THEN INSERT (CT.ADR_MAIL_UTIL) VALUES (:contactEmail)

Upvotes: 0

data_henrik
data_henrik

Reputation: 17118

The IMPORT command in Db2 has a INSERT_UPDATE option. You can read here about the IMPORT command.

If your data is already in the database then consider using the MERGE statement.

Both, in their context, to insert new and update existing data based on some rules.

Upvotes: 1

Related Questions