Possible Duplicate:
Oracle: how to UPSERT (update or insert into a table?)
Hi,
I have a table in which a record has to be modified if it already exists else a new record has to be inserted. Oracle sql doesnt accept IF EXISTS
, otherwise I would have done an if - update - else - insert
query. I've looked at MERGE
but it only works for multiple tables. What do i do?
You use the INSERT statement to insert or update a single row in an existing table. The word UPSERT combines UPDATE and INSERT , describing it statement's function. Use an UPSERT statement to insert a row where it does not exist, or to update the row with new values when it does.
The Oracle EXISTS condition is used in combination with a subquery and is considered "to be met" if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:
MERGE INTO mytable d USING (SELECT 1 id, 'x' name from dual) s ON (d.id = s.id) WHEN MATCHED THEN UPDATE SET d.name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);
Alternatively you can do this in PL/SQL:
BEGIN INSERT INTO mytable (id, name) VALUES (1, 'x'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN UPDATE mytable SET name = 'x' WHERE id = 1; END;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With