Created
July 23, 2012 07:42
-
-
Save theorigin/3162449 to your computer and use it in GitHub Desktop.
SQL Server MERGE statement
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
MERGE INTO Lookups AS Target | |
USING (VALUES | |
(0, N'Lookup Number 0'), | |
(1, N'Lookup Number 1'), | |
(2, N'Lookup Number 2'), | |
(3, N'Lookup Number 3'), | |
(4, N'Lookup Number 4'), | |
(5, N'Lookup Number 5'), | |
(6, N'Lookup Number 6') | |
) | |
AS Source (id, Name) | |
ON Target.LookupsID = Source.id | |
-- update matched rows | |
WHEN MATCHED THEN | |
UPDATE SET Name = Source.Name | |
-- insert new rows | |
WHEN NOT MATCHED BY TARGET THEN | |
INSERT (LookupsID, Name) | |
VALUES (id, Name) | |
-- delete rows that are in the target but not the source | |
WHEN NOT MATCHED BY SOURCE THEN | |
DELETE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment