I need to merge data from one table to another.
The data is delivered via flat files. That is why I use a load table first before moving it into production.
I add a field loadtabletime to the loadtables, so I can tell db2 only to merge one file at a time, even if more than one file is inserted in the load table at one time.
The load table is loaddlp.reservation_insert, and the production table is dlp.reservation.
This is my query:
MERGE INTO DLP.RESERVATION AS E
USING LOADDLP.RESERVATION_INSERT as et
on e.TICKET_SERVER = et.TICKET_SERVER
and e.RES_ID = et.RES_ID
and et.LOADTABLETIME = '2012-06-09 10:44:17.42236'
WHEN MATCHED THEN UPDATE SET (foo) = (bar)
WHEN NOT MATCHED THEN INSERT (xyz) VALUES (;akdjf)
the primary key for load table is ticket_server, res_id and loadtabletime; for prod table it’s ticket_server and res_id.
This query fails with the following error:
Could not Update data from the stage to production table RESERVATION.
[[23505] [IBM][CLI Driver][DB2/LINUXX8664] SQL0803N One or more
values in the INSERT statement, UPDATE statement, or foreign key
update caused by a DELETE statement are not valid because the primary
key, unique constraint or unique index identified by “1” constrains
table “DLP.RESERVATION” from having duplicate values for the index
key. SQLSTATE=23505
But, when I remove loadtabletime from the where clause it magically works. Of course, this is not an option as when multiple files are loaded into the load table, you could have pk violations on insert.
When I run:
SELECT count(*)
from loaddlp.reservation_insert
where LOADTABLETIME = '2012-06-09 10:44:17.42236';
I get the correct results.
Does anyone has an idea of what’s wrong with the query?
ok, I solved it.
The key was too add a select query in the ‘using’ field.
Example: