merge into 目标表 a
using 源表 b
on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)
when matched then update set a.更新字段=b.字段
when not macthed then insert into a(字段1,字段2……)values(值1,值2……)
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 = col_val2
WHEN NOT MATCHED THEN
INSERT (column_list) VALUES (column_values);
CREATE TABLE a_ace (
[id] int NULL ,
[name] varchar(20) NULL
)
【table】【a_ace】
INSERT INTO a_ace ([id], [name]) VALUES ('1', 'lisa');
INSERT INTO a_ace([id], [name]) VALUES ('2', 'tom');
INSERT INTO a_ace ([id], [name]) VALUES ('3', 'eddy');
【table】【a_ace1】
INSERT INTO a_ace ([id], [name]) VALUES ('1', 'lisa');
merge into a_ace1 a
using (select * from a_ace where id = 2) b
on a.id=b.id
when matched then
update set a.name = a.name+' '+a.name
when not matched THEN
insert values(b.id,b.name);
===============================
merge into a_ace1 a
using a_ace b
on a.id=b.id
when matched then
update set a.name = a.name+' '+a.name
when not matched THEN
insert values(b.id,b.name);