Using MERGE to insert/update in SQL Server

After finding various useless references on how to use the MERGE statement in SQL Server 2008, I found this one that I could use, so I copied it here for personal reference:

MERGE tablename AS target
USING (VALUES ('new value', 'different value'))
    AS source (field1, field2)
    ON target.idfield = 7
WHEN MATCHED THEN
    UPDATE SET
    field1 = source.field1,
    field2 = source.field2,
    ...
WHEN NOT MATCHED THEN
    INSERT ( idfield, field1, field2, ... )
    VALUES ( 7,  source.field1, source.field2, ... )

Leave a Reply

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