Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created April 15, 2013 14:39
Show Gist options
  • Select an option

  • Save ichiroku11/5388595 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/5388595 to your computer and use it in GitHub Desktop.
行が存在すればupdate、存在しなければinsertするmerge文のサンプル
use tempdb;
create table #Fruit(
Name nvarchar(3),
Price int,
constraint PK_Fruit primary key(Name));
go
create proc #UpsertFruit
@name nvarchar(3),
@price int
as
merge #Fruit as Target
using (values(@name, @price)) as Source(Name, Price)
on Target.Name = Source.Name
when matched then
update set Price = Source.Price
when not matched then
insert values(Source.Name, Source.Price);
go
insert into #Fruit
values ('りんご', 150), ('みかん', 120), ('バナナ', 100);
select * from #Fruit order by Price;
exec #UpsertFruit @name = N'みかん', @price = 180;
select * from #Fruit order by Price;
exec #UpsertFruit @name = N'いちご', @price = 160;
select * from #Fruit order by Price;
drop table #Fruit;
drop proc #UpsertFruit;
@ichiroku11

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment