Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Insert (if not exists) - MERGE, DUP_VAL_ON_INDEX, etc.

seggioneApr 23 2013 — edited Apr 23 2013
Hello,

i've an issue regarding scaling data in tables.

My Database-Version: Oracle Database 10g Release 10.2.0.5.0 - 64bit Production

My intention is to insert given data into TABLE1 if there's no equivalent data in TABLE2.

CREATE TABLE TABLE1
(
COLUMN1 NUMBER
, COLUMN2 NUMBER
);

CREATE TABLE TABLE1
(
COLUMN1 NUMBER
, COLUMN2 NUMBER
);

No data in both tables.

First attempt using the MERGE-statement:

DECLARE
v1 NUMBER := 1;
v2 NUMBER := 2;
BEGIN
MERGE INTO TABLE2 trgt
USING (SELECT COLUMN1, COLUMN2 FROM TABLE1 WHERE COLUMN1=v1 AND COLUMN2=v2) src
ON (trgt.COLUMN1 = src.COLUMN1 AND trgt.COLUMN2 = src.COLUMN2)
WHEN NOT MATCHED THEN
INSERT (COLUMN1, COLUMN2)
VALUES (v1, v2);
COMMIT;
END;

I thought it should be possible because there is NO MATCH, because the USING-statements returns no rows.
Now i know, the data merged into TABLE2 results from the source-query.

This works neither:
INSERT INTO TABLE2 (COLUMN1, COLUMN2)
VALUES (v1, v2)
WHERE NOT EXISTS (SELECT * FROM TABLE1 WHERE COLUMN1=v1 AND COLUMN2=v2)

Is there any other solution, except row-counting in TABLE1 or using the DUP_VAL_ON_INDEX-Exception-"way"?

Thank you very much!

Best regards,

André
This post has been answered by Frank Kulash on Apr 23 2013
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 21 2013
Added on Apr 23 2013
3 comments
18,262 views