Usage of MERGE INTO in ORACLE

Usage of MEGER INTO in ORACLE

Usage scenario:
When operating the database, UPDATE if the data exists, and INSERT if the data does not exist. The ORACLE database provides the MERGE method to handle this requirement.

MERGE command:
The MERGE command uses one statement to update and insert data into a table from one or more data sources.

MERGE syntax:

MERGE INTO [your table-name] [rename your table here] 
USING ( [write your query here] )[rename your query-sql and using just like a table] 
ON ([conditional expression here] AND [...]...) 
WHEN MATCHED THEN [here you can execute some update sql or something else ] 
WHEN NOT MATCHED THEN [execute something else here ! ] 

Demo:

MERGE INTO  DEMO T
USING (SELECT '1' ID, 'wangyi' NAME FROM dual) P on (T.ID=P.ID)
WHEN MATCHED THEN UPDATE SET T.NAME=P.NAME
WHEN NOT MATCHED THEN  INSERT (T.ID, T.NAME) VALUES (P.ID, P.NAME ); 

If the data with ID 1 exists, it will be updated, if it does not exist, it will be inserted

Warning:

The principle of Merge Into is that the results searched from using match the on condition one by one, and then decide whether to update or insert.
When the SQL behind USING does not query data, the Merge Into statement will not perform update and Insert operations. Therefore, in order to make Merge
Into run normally, it is necessary to ensure that the SELECT after USING has data.

Interesting
MEGER INTO UPDATE can be used when the execution efficiency of batch Update is very low

Guess you like

Origin blog.csdn.net/qq_37980551/article/details/105246064