In the common operations of the Oracle database, sometimes it is necessary to use the B table to update the content in the A table. One method is to use update to associate two tables to update, and another method is to use merge into.
Merge into a statement can realize the functions of update and insert, and it is more efficient
grammar
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 MATHED THEN [here you can execute some update sql or something else ]
WHEN NOT MATHED THEN [execute something else here ! ]
Example
Create table test_sj_salary, insert sample data
create table test_sj_salary ( id integer primary key, name varchar2(100), salary integer ); truncate table test_sj_salary; insert into test_sj_salary (ID, NAME, SALARY) values (1, 'Zhang San', 5000); insert into test_sj_salary (ID, NAME, SALARY) values (2, 'Li Si', 4000); insert into test_sj_salary (ID, NAME, SALARY) values (3, 'Wang Wu', 6000); insert into test_sj_salary (ID, NAME, SALARY) values (4, 'Li Liu', 3500); commit;
Build test_sj_cp, insert sample data
create table test_sj_cp ( id integer primary key, name varchar2(100), salary integer ); truncate table test_sj_cp; insert into test_sj_cp (ID, NAME, SALARY) values (9, 'Zhang San', 9000); insert into test_sj_cp (ID, NAME, SALARY) values (10, 'Li Si', 10000); insert into test_sj_cp (ID, NAME, SALARY) values (11, 'Wang Ermazi', 11000); commit;
Function to be implemented: use test_sj_cp to update the salary field in test_sj_salary according to the same name
Method 1, using the ordinary update method
update test_sj_salary a set a.salary=(select b.salary from test_sj_cp b where b.name=a.name) where exists (select 1 from test_sj_cp c where c.name=a.name); commit;
Method 2, using the merge into method
merge into test_sj_salary a using test_sj_cp b on (a.name=b.name) when matched then update set a.salary=b.salary; commit;
Isn't it very concise!
Extended function, through merge to achieve matching updates, unmatched insert data
merge into test_sj_salary a using test_sj_cp b on (a.name=b.name) when matched then update set a.salary=b.salary when not matched then insert(id,name,salary) values(b.id,b.name,b.salary); commit;