| Subcribe via RSS

Tutorial : DB2 V9 MERGE (A.K.A UPSERT)

August 4th, 2009 Posted in DB2

Well, I am not a DBA and I don’t know something like this very much. But my company encourage me to take a course on DB2 V.9. And I have one command that I wanted to remember and I know that it will benefit me later on. MERGE

So, basically, you have to table and you want to merge it together. I will explain it in a real table.

T1 M1
ID AMOUNT
1 100
2 200
.
ID AMOUNT
1 100
2 200
3 200

So, we have two tables, M1 and T1. T1 has a row number 3 that M1 doesn’t have. So, if you run the MERGE command. First DB2 will UPDATE everything that the first table has in the second table. Moreover, a little bit more extra in T1 row number 3 that M1 doesn’t have. DB2 will INSERT it into T1.

Therefore, this will save you a huge amount of time to do SELECT whether T1 has row number and M1 has row number and UPDATE it. And check again and again. You could do it in one command.

1
2
3
4
5
6
7
8
MERGE INTO M1
USING ( SELECT ID, AMOUNT FROM M1 )
AS T1 (ID, AMOUNT)
ON ( M1.ID = T1.ID )
WHEN MATCHED THEN
 UPDATE SET AMOUNT = AMOUNT + T1.AMOUNT
WHEN NOT MATCHED THEN
 INSERT ( ID, AMOUNT ) VALUES (T1.ID, T1.AMOUNT);

2 Responses to “Tutorial : DB2 V9 MERGE (A.K.A UPSERT)”

  1. Adam Says:

    Hi

    Sub : Tech Blog Link Request – http://www.adamsinfo.com

    For leveraging traffic from the internet, I have manually collected a list of quality blogs and sites with whom I am interested in getting associated.

    I liked your Site/blog and i’m interested in having my blog’s text link in your blog roll.

    Please let me know your interest in this association and then we can move towards next step.

    Sincerely,

    Webmaster
    Adamsinfo.com
    seo@apnicsolutions.com


  2. Freaking_crack Says:

    Yes, I am.


Leave a Reply