MERGE语句,它可以在一个SQL语句中对一张表或一个视图同时做更新或插入操作,避免了多个INSERT、UPDATE和DELETE语句。它可以从一个或多个数据源中选择数据对目标表做更新或插入操作,你可以指定在何种条件下更新或插入目标表或视图。不可以对同一行做多次更新操作。例如:实现用B表来更新A表数据,如果A表中没有,则把B表的数据插入A表。
Oracle 11gR2语法如下:
MERGE [ hint ]
INTO [ schema. ] { table | view } [ t_alias ]
USING { [ schema. ] { table | view }
| subquery
} [ t_alias ]
ON ( condition )
[ merge_update_clause ]
[ merge_insert_clause ]
[ error_logging_clause ] ;
#merge_update_clause
WHEN MATCHED THEN
UPDATE SET column = { expr | DEFAULT }
[, column = { expr | DEFAULT } ]...
[ where_clause ]
[ DELETE where_clause ]
#merge_insert_clause
WHEN NOT MATCHED THEN
INSERT [ (column [, column ]...) ]
VALUES ({ expr | DEFAULT }
[, { expr | DEFAULT } ]...
)
[ where_clause ]
#error_logging_clause
LOG ERRORS
[ INTO [schema.] table ]
[ (simple_expression) ]
[ REJECT LIMIT { integer | UNLIMITED } ]
使用例子说明MERGE语句的作用:
创建测试表emp_m
scott@TEST>create table emp_m as select * from emp where comm is not null;
Table created.
scott@TEST>select * from emp_m;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ------------------------------ --------------------------- ---------- ------------------- ---------- ---------- ----------
7499 ALLEN SALESMAN 7698 1981-02-20 00:00:00 1600 300 30
7521 WARD SALESMAN 7698 1981-02-22 00:00:00 1250 500 30
7654 MARTIN SALESMAN 7698 1981-09-28 00:00:00 1250 1400 30
7844 TURNER SALESMAN 7698 1981-09-08 00:00:00 1500 0 30
例子1:插入和更新操作
现在测试表emp_m中只有comm不为空的数据,现在要把在emp表而不在emp_m表中的数据插入到emp_m表中,并把emp_m表中现有的数据的comm增加10。
scott@TEST>MERGE INTO EMP_M M
2 USING EMP N
3 ON (M.EMPNO = N.EMPNO)
4 WHEN NOT MATCHED THEN
5 INSERT
6 (M.EMPNO, M.ENAME, M.JOB, M.MGR, M.HIREDATE, M.SAL, M.COMM, M.DEPTNO)
7 VALUES
8 (N.EMPNO, N.ENAME, N.JOB, N.MGR, N.HIREDATE, N.SAL, N.COMM, N.DEPTNO)
9 WHEN MATCHED THEN
10 UPDATE SET M.COMM = M.COMM + 10;
14 rows merged.
scott@TEST>select * from emp_m;