Oracle 用 Merge 進行兩個 Table 之間的資料比對

在 Oracle Database 中, 若要進行兩個 Table 之間的資料比對,

當目的不存在來源時, 則做 Insert

當目的存在於來源時, 則做 Update

該怎麼做呢 ?

Oracle 提供 Merge 語法可以達成,

如下範例 :
 範例程式碼
-- 建立來源 Temp Table
create table tomSour (
aa number
, bb varchar2(100)
);

-- 建立要比對的目的 Temp Table
create table tomDest (
aa number
, bb varchar2(100)
);

-- 新增來源資料
insert into tomSour values( 1, '100' );
insert into tomSour values( 2, '200' );
insert into tomSour values( 3, '300' );
insert into tomSour values( 4, '400' );
insert into tomSour values( 5, '500' );

-- 新增目的資料
insert into tomDest values( 1, 'abc' );
insert into tomDest values( 3, 'xyz' );

-- 開始比對
-- 若存在於來源, 則更改目的 Table 的 bb 欄位
-- 若不存在於來源, 則新增到目地 Table

begin
merge into tomDest d
using tomSour s
on (d.aa = s.aa)
when MATCHED then
update set
d.bb = d.bb || ' to ' || s.bb
when NOT MATCHED then
insert (aa, bb ) values( s.aa, 'New: '||s.bb );

end;

-- 查看目的資料
select *
from tomDest;

-- 查詢結果 :
1 abc to 100
2 New: 200
3 xyz to 300
4 New: 400
5 New: 500
Related Posts Plugin for WordPress, Blogger...