-
[SQL] Oracle Merge Into 사용법programming/SQL 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 charactersCREATE 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 charactersINSERT 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 charactersMERGE 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 charactersMERGE 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); 반응형'programming > SQL' 카테고리의 다른 글
[Oracle] 오라클 날짜 포맷 사용(TO_CHAR) (0) 2021.07.20 [Oracle] Date 24시간으로 비교하기 (0) 2020.12.23 [ORACLE] 오라클 시퀀스 에러 CURRVAL, NEXTVAL (0) 2020.04.22 [오라클] 숫자에 콤마 찍기 (0) 2019.12.27 [Mybatis] 마이바티스 부등호 표시 (0) 2019.12.12