Created
April 15, 2013 14:39
-
-
Save ichiroku11/5388595 to your computer and use it in GitHub Desktop.
行が存在すればupdate、存在しなければinsertするmerge文のサンプル
This file contains hidden or 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
| 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; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://ichiroku11.hatenablog.jp/entry/2013/04/15/234650