Example of usage of Merge into in Oracle

Recently, I have been working on a request, which involves the problem of tables. The front end sends a piece of data. According to the primary key, the database is queried. If it does not exist, it will be inserted into the database for a long time. If it exists, it is the primary key. data to update.

When I got this requirement, I thought of directly using the if...else... code to make judgments. The first is to query. If the record is found, it will be updated. If it is not found, the data will be inserted directly.

There is no problem with this method. After all, it can complete the requirements. However, because the records of this table in the database are really too large, it is too time-consuming to query and judge by means of code. After a query, this is the method to find the merge into of the Oracle database.

First, let's take a look at the basic syntax of merge into (a feature introduced in Oracle 9i):

MERGE INTO table_name alias1

USING (table|view|sub_query) alias2

ON (join condition)

WHEN MATCHED THEN

UPDATE table_name

SET col1 = col_val1, col2 = col_val2

WHEN NOT MATCHED THEN

INSERT (column_list) VALUES (column_values);   


Maybe you don't know much about this syntax, so let's look at a simple example now:

merge into Students st using newStudents nst on (st.id = nst.id)

when matched then

update set st.name = nst.name

when not matched then

insert values(nst.id, nst.name, nst.sex)


The meaning of this sql means that if the id of the new student already exists in the database, when it is matched, the update operation is performed; when it is not matched, the insert operation is performed.

Compared with using code judgment to perform update or insert operations, the execution of SQL statements has undoubtedly been improved in terms of efficiency, so using merge into is still a good choice.

Because I am not familiar with the database, I didn't think of this kind of operation at the first time. I used it this time, and it was considered as learning. Record it, maybe it will be useful in the future.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326125049&siteId=291194637