Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding conditions in MERGE statement in Oracle SQL for INSERT/UPDATE

Tags:

I have to insert/update some RECORDS in table target_table. These records are coming one source_table.

I am using MERGE for update/insert the target_table.

MERGE    INTO  target_table tgt    USING source_table src    ON  ( src.column1 = tgt.column1 and          src.column2 = tgt.column2) WHEN MATCHED THEN    UPDATE    SET   tgt.column3= src.column3,          tgt.column4 = src.coulmn4    WHEN NOT MATCHED    THEN INSERT ( tgt.column1,          tgt.column2,          tgt.column3,          tgt.column4 ) VALUES ( src.coulmn1,          src.coulmn2,          src.coulmn3,          src.coulmn4); 

I want to add some specific condition on update.

IF target_table.column3 in (val1','val2)

then only there should be update, else no update or insert.

like image 716
Bit_hunter Avatar asked Jan 25 '13 10:01

Bit_hunter


People also ask

Can we add WHERE condition in MERGE statement?

The MERGE statement doesn't have a WHERE clause.

Can we use if condition in MERGE statement in SQL?

If table exists is fine. Because the table doesn't exist so it can't compile your query. You either need to ensure the table will exist or move the query to be inside dynamic sql. When you run something, a query plan is made for each and every statement, including those that are inside if blocks.

Can we use WHERE clause in MERGE statement in Oracle?

where_clause - You must specify the where_clause if you want Oracle to execute the update operation only if the specified condition is true. The WHERE condition can apply to either the data source or the target table. If the condition is false, the update operation is skipped when merging the row into the target table.

Can we use with clause in MERGE statement?

At most, we can specify only two WHEN MATCHED clauses in the MERGE statement. If two WHEN MATCHED clauses are specified, one clause must have an update operation and the other one must use delete operation.


2 Answers

You can simply add WHERE clause to UPDATE. More about it in oracle docs.

So in your case it should look like:

... WHEN MATCHED THEN    UPDATE    SET   tgt.column3= src.column3,          tgt.column4 = src.coulmn4    WHERE tgt.column3 IN (val1, val2)  WHEN NOT MATCHED ... 
like image 171
psur Avatar answered Oct 05 '22 14:10

psur


Instead Try Doing As below:

MERGE INTO  target_table tgt USING source_table src ON  (src.column1 = tgt.column1) WHEN MATCHED THEN UPDATE SET   tgt.column3= src.column3,      tgt.column4 = src.coulmn4   WHERE src.column1 = tgt.column1 and      src.column2 = tgt.column2 WHEN NOT MATCHED THEN INSERT ( tgt.column1,      tgt.column2,      tgt.column3,      tgt.column4 ) VALUES ( src.coulmn1,      src.coulmn2,      src.coulmn3,      src.coulmn4); 
like image 25
Somashekhar Dhanashree Avatar answered Oct 05 '22 14:10

Somashekhar Dhanashree