Let's say I have a table named FRUITS like this:
| ID | PRODUCT | ACTIVE |
|---|---|---|
| 1 | apple | 1 |
| 1 | orange | 1 |
| 2 | orange | 0 |
(ID = 1 has two PRODUCTS, and both have ACTIVE = 1).
Now I want output in same table like this:
| ID | PRODUCT | ACTIVE |
|---|---|---|
| 1 | apple | 1 |
| 1 | orange | 1 |
| 2 | orange | 1 |
| 2 | apple | 1 |
So what I need is to Insert or Update values in a table, based on a condition for PRODUCT and ID from same table.
Or in another words - I want to copy all columns from existing ID into rows of given ID with same PRODUCT (UPDATE) or INSERT if rows with same PRODUCT doesn't exist under given ID.
Is there a way that this could be done with a single statement, like MERGE?
I tried with this MERGE statement, but It doesn't work:
MERGE INTO fruits d
USING (SELECT id,
product,
active
FROM fruits
WHERE id = :old_id_in) s
ON (d.id = :new_id_in AND d.product = s.product)
WHEN MATCHED THEN
UPDATE SET d.product = s.product,
d.active = s.active
WHERE d.id = :new_id_in
WHEN NOT MATCHED THEN
INSERT (d.id, d.product, d.active)
VALUES(:new_id_in, s.product, s.active);
Any help appreciated !
You can use:
Which, for the sample data:
Then, after the
MERGEthe table contains:fiddle