MERGE 使用例子

--MERGE <Usage Case>

--Prepare the temp table to test
DROP TABLE wl_merge_tb1;
DROP TABLE wl_merge_tb2;
CREATE TABLE wl_merge_tb1 (tb_id NUMBER, tb_name VARCHAR2 (10));
CREATE TABLE wl_merge_tb2 (tb_id NUMBER, tb_name VARCHAR2 (10));

--Prepare the temp data to test
--The target table data
INSERT INTO wl_merge_tb1 VALUES (1,'a1');
INSERT INTO wl_merge_tb1 VALUES (2,'a2');
INSERT INTO wl_merge_tb1 VALUES (3,'a3');
INSERT INTO wl_merge_tb1 VALUES (4,'a4');
INSERT INTO wl_merge_tb1 VALUES (5,'a5');
--The source table data
INSERT INTO wl_merge_tb2 VALUES (1,'b1');
INSERT INTO wl_merge_tb2 VALUES (2,'b2');
INSERT INTO wl_merge_tb2 VALUES (3,'b3');
INSERT INTO wl_merge_tb2 VALUES (4,'b4');
INSERT INTO wl_merge_tb2 VALUES (6,'b6');
COMMIT;
--The MERGE clause
MERGE INTO wl_merge_tb1 t1
--Declare the data source
USING ( SELECT t.tb_id
             , t.tb_name
        FROM wl_merge_tb2 t
      ) t2
   --Set the relationship between the source and target table
   ON ( t1.tb_id = t2.tb_id ) 
 --The matched data of source and target table
 WHEN MATCHED THEN
     --Update the target table use the source table data
     UPDATE SET t1.tb_name = 'update'||t2.tb_name
      --Set the action execute condition
      WHERE ( t1.tb_id < 5 )
     --Delete the record of the matched data under the 'WHERE' condition
     DELETE WHERE ( t1.tb_id > 2 )
 --The not matched data in source data table
 WHEN NOT MATCHED THEN
     --Insert the source record to the target table,alse you can set 'WHERE' condition
     INSERT ( t1.tb_id, t1.tb_name )
     VALUES ( t2.tb_id, 'insert' || t2.tb_name );
COMMIT;
    
SELECT * FROM wl_merge_tb1;
SELECT * FROM wl_merge_tb2;

--Target table data
1    updateb1
2    updateb2
5    a5
6    insertb6

--Source table data
1    b1
2    b2
3    b3
4    b4
6    b6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值