Is there a way to use the instruction:
MERGE INTO MySchema.MyTable AS Target
USING (VALUES
........
)
With nothing instead of the dots? Usually you have there something like a list of (firstValue, SecondValue,...,LastValue), one for each row you want to merge but I'd like to be able to write the instruction with NO rows so that the DELETE part of the MERGE deletes all the rows.
This is because I am using a stored procedure that creates the MERGE
instruction automatically but sometimes the table that i am starting from is empty.
Of course I tried with:
MERGE INTO MySchema.MyTable AS Target USING (VALUES)
but it is not accepted.
Example:
MERGE INTO [dbo].[MyTable] AS Target
USING (VALUES (1,'Attivo') ,(2,'Disabilitato') ,(3,'Bloccato') ) AS Source ([IDMyField],[MyField]) ON (Target.[IDMyField] = Source.[IDMyField])
WHEN MATCHED AND ( NULLIF(Source.[MyField], Target.[MyField]) IS NOT NULL OR NULLIF(Target.[MyField], Source.[MyField]) IS NOT NULL)
THEN UPDATE SET [MyField] = Source.[MyField]
WHEN NOT MATCHED BY TARGET
THEN INSERT([IDMyField],[MyField]) VALUES(Source.[IDMyField],Source.[MyField])
WHEN NOT MATCHED BY SOURCE
THEN DELETE;