在批处理任务中,可能需要对目标表进行大量 INSERT 或 UPDATE。如果需求是记录不存在就 INSERT,存在就 UPDATE,此时可以使用 MERGE 语句。
MERGE 语句的语法简单描述如下:
MERGE INTO table_name alias1
USING (table|view|sub_query) alias2
ON (join condition)
WHEN MATCHED THEN
UPDATE table_name
SET col1 = col_val1 ,
col2 = col2_val
WHEN NOT MATCHED THEN
INSERT (column_list) VALUES (column_values);
使用示例如下:
obclient> CREATE TABLE t_merge(
id number NOT NULL PRIMARY KEY,
name varchar2(50) NOT NULL,
value number NOT NULL,
gmt_create date NOT NULL DEFAULT sysdate,
gmt_modified date NOT NULL DEFAULT sysdate
);
Query OK, 0 rows affected (0.06 sec)
obclient> INSERT INTO t_merge(id,name,value) values(1,'CN',1),(2,'US',2);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
obclient> MERGE INTO t_merge t2
USING (SELECT id,name,value,gmt_create FROM t_insert ) t1
ON (t2.id=t1.id)
WHEN MATCHED THEN
UPDATE SET t2.name=t1.name, t2.value=t1.value, t2.gmt_modified=sysdate
WHEN NOT MATCHED THEN
INSERT (t2.id,t2.name,t2.value) values(t1.id, t1.name, t1.value)
;
Query OK, 3 rows affected (0.01 sec)
obclient> select * from t_merge;
+----+------+-------+---------------------+---------------------+
| ID | NAME | VALUE | GMT_CREATE | GMT_MODIFIED |
+----+------+-------+---------------------+---------------------+
| 1 | CN | 10001 | 2020-04-02 17:51:59 | 2020-04-02 17:52:52 |
| 2 | US | 10002 | 2020-04-02 17:51:59 | 2020-04-02 17:52:52 |
| 3 | EN | 10003 | 2020-04-02 17:52:52 | 2020-04-02 17:52:52 |
+----+------+-------+---------------------+---------------------+
3 rows in set (0.01 sec)