Merging Rows Using MERGE
MERGE
statement merges rows from one table into another.
MERGE INTO
specifies the name of the table to merge the rows into.
USING ... ON
specifies a table join.
WHEN MATCHED THEN
tells what to do when the USING...ON
is satisfied for a row.
WHEN NOT MATCHED THEN
tells what to do when the USING...ON
is not satisfied for a row.
CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
SAL NUMBER(7, 2),
DEPTNO NUMBER(2));
INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250, 30);
INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER', 2850, 30);
INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER', 2850, 10);
INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST', 3000, 20);
INSERT INTO EMP VALUES (9, 'KING', 'PRESIDENT',3000, 10);
INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500, 30);
INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK', 1500, 20);
CREATE TABLE AnotherEMP (EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
SAL NUMBER(7, 2),
DEPTNO NUMBER(2));
INSERT INTO AnotherEMP VALUES (1, 'SMITH', 'CLERK', 800, 20);
INSERT INTO AnotherEMP VALUES (2, 'ALLEN', 'SALESMAN', 1600, 30);
INSERT INTO AnotherEMP VALUES (3, 'WARD', 'SALESMAN', 1250, 30);
INSERT INTO AnotherEMP VALUES (4, 'JONES', 'MANAGER', 2975, 20);
SQL> MERGE INTO emp p
2 USING anotherEmp pc ON (p.empno = pc.empno)
3 WHEN MATCHED THEN
4 UPDATE
5 SET p.ename = pc.ename
6 WHEN NOT MATCHED THEN
7 INSERT (p.empno, p.ename) VALUES (pc.empno, pc.ename);
4 rows merged.
SQL>
SQL> select * from emp;
EMPNO ENAME JOB SAL DEPTNO
---------- ---------- --------- ---------- ----------
5 MARTIN SALESMAN 1250 30
6 BLAKE MANAGER 2850 30
7 CLARK MANAGER 2850 10
8 SCOTT ANALYST 3000 20
9 KING PRESIDENT 3000 10
10 TURNER SALESMAN 1500 30
11 ADAMS CLERK 1500 20
4 JONES
3 WARD
1 SMITH
2 ALLEN
11 rows selected.
SQL>