Difference between revisions of "Oracle/Merge"
Jump to navigation
Jump to search
(New page: The Oracle '''MERGE'' statement may be used for various purposes. Its main function is to merge data from one table (or view) into another table. Inserts and Updates can be performed, ...) |
|||
| (6 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
The [[Oracle]] '''MERGE'' statement may be used for various purposes. Its main function is to merge data from one table (or view) into another table. Inserts and Updates can be performed, Deletes are available since Oracle 10g. | The [[Oracle]] '''MERGE''' statement may be used for various purposes. Its main function is to merge data from one table (or view) into another table. Inserts and Updates can be performed, Deletes are available since Oracle 10g. | ||
'''Merge new and updated client data from table ''client_new'' into table ''client'':''' | |||
<source lang="oracle11"> | |||
MERGE INTO clients c | |||
USING (SELECT id, name, address_id FROM clients_new) cn | |||
ON (cn.id = c.id) | |||
WHEN MATCHED THEN -- update existing | |||
UPDATE SET c.name = cn.name, e.address_id = cn.address_id | |||
WHEN NOT MATCHED THEN -- create missing (new) | |||
INSERT (c.id, c.name, c.address_id) | |||
VALUES (cn.id, cn.name, cn.address_id); -- we assume that there will be no id conflicts! | |||
</source> | |||
'''An optional Delete clause will be executed if the Delete's WHEN clause and the Merge's ON clause match:''' | |||
<source lang="oracle11"> | |||
MERGE into t | |||
using dual | |||
on (dummy=x) | |||
when matched then | |||
update set y = nvl(y, 0)+1 | |||
delete where y = 2 | |||
when not matched then | |||
insert (x,y) | |||
values (dummy, null); | |||
</source> | |||
An example for Update using join and merge may be found [[Oracle/Update join|here]]. | |||
[[Category:Oracle]] | [[Category:Oracle]] | ||
Latest revision as of 12:24, 29 April 2010
The Oracle MERGE statement may be used for various purposes. Its main function is to merge data from one table (or view) into another table. Inserts and Updates can be performed, Deletes are available since Oracle 10g.
Merge new and updated client data from table client_new into table client:
MERGE INTO clients c
USING (SELECT id, name, address_id FROM clients_new) cn
ON (cn.id = c.id)
WHEN MATCHED THEN -- update existing
UPDATE SET c.name = cn.name, e.address_id = cn.address_id
WHEN NOT MATCHED THEN -- create missing (new)
INSERT (c.id, c.name, c.address_id)
VALUES (cn.id, cn.name, cn.address_id); -- we assume that there will be no id conflicts!
An optional Delete clause will be executed if the Delete's WHEN clause and the Merge's ON clause match:
MERGE into t
using dual
on (dummy=x)
when matched then
update set y = nvl(y, 0)+1
delete where y = 2
when not matched then
insert (x,y)
values (dummy, null);
An example for Update using join and merge may be found here.