Last active
November 29, 2018 12:09
-
-
Save coffman21/5a121cacfc884976292d6bacfbb31896 to your computer and use it in GitHub Desktop.
sql server merge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create table source | |
( | |
id int not null primary key identity (1,1), | |
a varchar, | |
b varchar | |
); | |
select * from source | |
create table target | |
( | |
id int not null primary key identity (1,1), | |
a varchar, | |
b varchar | |
); | |
insert into source values ('1', '1'); | |
insert into source values ('2', '3'); | |
insert into source values ('3', '4'); | |
insert into source values ('4', '5'); | |
insert into target values ('1', NULL); | |
insert into target values ('2', NULL); | |
insert into target values ('3', NULL); | |
insert into target values ('4', NULL); | |
merge target t using (select a,b from source) as s(a,b) on (t.a = s.a) | |
when matched then | |
update set b = s.b | |
when not matched then | |
insert (a, b) values (s.a, s.b) | |
output deleted.*, inserted.* ; | |
select * from target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment