programming/SQL
[SQL] Oracle Merge Into 사용법
LeeBorn
2020. 6. 4. 22:32
반응형

오라클에서 테이블에 데이터를 Insert 할 때, 또는 두 개의 테이블을 합칠 때,
이미 테이블에 데이터가 있으면 Update를, 테이블에 데이터가 없으면 Insert를,
하기 위해선 MERGE INTO를 사용할 수 있다.
예를 들어서 아래와 같은 테이블과 데이터들이 있을 때,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE MERGE1( | |
NO NUMBER, | |
name varchar2(100), | |
phone varchar2(100), | |
age number | |
); | |
CREATE TABLE MERGE2( | |
NO NUMBER, | |
name varchar2(100), | |
phone varchar2(100), | |
age number | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSERT INTO MERGE1 VALUES(1, 'AAA', '010-1111-1111', 10); | |
INSERT INTO MERGE1 VALUES(2, 'BBB', '010-1111-1111', 10); | |
INSERT INTO MERGE2 VALUES(2, 'BBB', '010-2222-2222', 20); |
아래와 같이 MERGE INTO를 사용할 수 있다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MERGE INTO MERGE1 M1 | |
USING MERGE2 M2 | |
ON (M1.NO = M2.NO) | |
WHEN MATCHED THEN | |
UPDATE SET AGE = 100 | |
WHEN NOT MATCHED THEN | |
INSERT (M1.NO, M1.NAME, M1.PHONE, M1.AGE) | |
VALUES(3, 'CCC', '010-3333-4444', 30); |
두 개의 테이블이 없고, 어떤 값들을 직접 비교할 때는 DUAL을 사용해서 데이터를 Insert 할 수 있다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MERGE INTO MERGE1 M1 | |
USING DUAL | |
ON (M1.NO = 2) | |
WHEN MATCHED THEN | |
UPDATE SET AGE = 200 | |
WHEN NOT MATCHED THEN | |
INSERT (M1.NO, M1.NAME, M1.PHONE, M1.AGE) | |
VALUES(3, 'CCC', '010-3333-4444', 30); |
반응형