MERGE可以合并多个表中的数据,也可实现多表中数据的同步。使用MERGE语句对表中数据进行有条件的更新和插入。当查找的行存在时,UPDATE更新行中的数据;当查找的行不存在时,INSERT插入数据。
语法如下:
MERGE INTO table_name table_alias
USING (table|view|sub_query) alias
ON (join condition)
WHEN MATCHED THEN
UPDATE SET
col1=col_val1,
col2=col_val2
WHEN NOT MATCHED THEN
INSERT (column_list)
VALUES (column_values);
语法解析:
MERGE INTO后跟要更新或者插入数据的目标表;
USING后跟源表;
ON后跟连接条件;
例如:同步dept表中数据到dept_1中
SQL> merge into dept_1 d1
2 using dept d
3 on (d.deptno=d1.deptno)
4 when matched then
5 update set d1.dname = d.dname, d1.loc = d.loc
6 when not matched then
7 insert values (d.deptno, d.dname, d.loc);
4 rows merged.
注意:ON后面作为连接条件的列不必再从SET后出现,即不能更新作为条件的列。否则会报如下错误:
SQL> merge into dept_1 d1
2 using dept d
3 on (d.deptno=d1.deptno)
4 when matched then
5 update set d1.deptno = d.deptno, d1.dname = d.dname, d1.loc = d.loc
6 when not matched then
7 insert values (d.deptno, d.dname, d.loc);
on (d.deptno=d1.deptno)
*
ERROR at line 3:
ORA-38104: Columns referenced in the ON Clause cannot be updated: "D1"."DEPTNO"