Oracle PL/SQL 利用 Merge 進行兩個 Table 之間的資料比對與備份



在 Oracle PL/SQL 中, 可以利用 Merge 進行新增 OR 修改資料的處理,

若資料存在於來源 Table, 則要作何處理 (如修改資料),

若資料不存在來源 Table, 則要作何處理 (如新增資料),

詳細範例, 如下 :
 程式碼
-- 建立來源 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...