SQL Server merge statement

The merge statement allows you to perform CRUD operations in a single query:

MERGE
	[Current_Offer_Counts] AS [Target]
USING
	[Get_Total_Usage] (param, NULL) AS [Source]
ON
	[Target].[ID] = [Source].[ID]
WHEN MATCHED AND [Target].[Count_days] != [Source].[total_usage] THEN
	UPDATE SET [Count_days] = [Source].[total_usage]
WHEN NOT MATCHED BY TARGET THEN 
	INSERT ([ID], [Count_days]) VALUES ([Source].[ID], [Source].[total_usage])
WHEN NOT MATCHED BY SOURCE THEN 
	DELETE

Leave a Reply

Your email address will not be published. Required fields are marked *