有兩個表名:source 表和 target 表,而且要根據 source 表中匹配的值更新 target 表。ui
有三種狀況:spa
下圖,說明了 source 表和 target 表 的一些操做:插入,更新,刪除:code
若是單獨使用 INSERT, UPDATE和DELETE語句,則須要三個單獨的語句,來使 source 表中的匹配行的數據更新到 target表。blog
可是,使用 merge 能夠同時執行三個操做。下面是 merge語句的語法:get
MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED
THEN update_statement
WHEN NOT MATCHED
THEN insert_statement
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
使用示例:it
CREATE TABLE sales.category ( category_id INT PRIMARY KEY, category_name VARCHAR(255) NOT NULL, amount DECIMAL(10 , 2 ) ); INSERT INTO sales.category(category_id, category_name, amount) VALUES(1,'Children Bicycles',15000), (2,'Comfort Bicycles',25000), (3,'Cruisers Bicycles',13000), (4,'Cyclocross Bicycles',10000); CREATE TABLE sales.category_staging ( category_id INT PRIMARY KEY, category_name VARCHAR(255) NOT NULL, amount DECIMAL(10 , 2 ) ); INSERT INTO sales.category_staging(category_id, category_name, amount) VALUES(1,'Children Bicycles',15000), (3,'Cruisers Bicycles',13000), (4,'Cyclocross Bicycles',20000), (5,'Electric Bikes',10000), (6,'Mountain Bikes',10000);
要使用 sales.category_staging(源表)中的值將數據更新到 sales.category(目標表),要使用 merge:io
MERGE sales.category t USING sales.category_staging s ON (s.category_id = t.category_id) WHEN MATCHED THEN UPDATE SET t.category_name = s.category_name, t.amount = s.amount WHEN NOT MATCHED BY TARGET THEN INSERT (category_id, category_name, amount) VALUES (s.category_id, s.category_name, s.amount) WHEN NOT MATCHED BY SOURCE THEN DELETE;
執行過程以下圖:table