Skip to content

Instantly share code, notes, and snippets.

@blzzua
Created July 3, 2024 16:22
Show Gist options
  • Save blzzua/86344f2d85c4582cc77a0f50538cc155 to your computer and use it in GitHub Desktop.
Save blzzua/86344f2d85c4582cc77a0f50538cc155 to your computer and use it in GitHub Desktop.
ms sql merge
MERGE targettable AS target
USING
(
select id, sub_id, somevalue from sometable_or_query
)
AS source
ON (target.id = source.id AND target.sub_id = source.sub_id)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
WHEN MATCHED THEN
UPDATE SET target.somevalue = source.somevalue
WHEN NOT MATCHED BY target THEN
INSERT (id,sub_id,somevalue) VALUES (source.id, source.sub_id, source.somevalue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment