RockScience RockScience - 28 days ago 12
SQL Question

SQL Server MERGE without a source table

I am learning how to use SQL Server MERGE statement from this page:
https://technet.microsoft.com/en-us/library/bb522522(v=sql.105).aspx

MERGE dbo.FactBuyingHabits AS Target
USING (SELECT CustomerID, ProductID, PurchaseDate FROM dbo.Purchases) AS Source
ON (Target.ProductID = Source.ProductID AND Target.CustomerID = Source.CustomerID)

WHEN MATCHED THEN
UPDATE SET Target.LastPurchaseDate = Source.PurchaseDate

WHEN NOT MATCHED BY TARGET THEN
INSERT (CustomerID, ProductID, LastPurchaseDate)
VALUES (Source.CustomerID, Source.ProductID, Source.PurchaseDate)

OUTPUT $action, Inserted.*, Deleted.*;


However all the examples I can find (such as the one above) are using an actual table as Source. Is it possible to directly pass the data? I would rather not create a temporary table for that (if possible and recommended?)
How would the query above be modified?

Thank you

Answer

Try this format:

MERGE TARGET_TABLE AS I
USING (VALUES ('VALUE1','VALUE2')) as s(COL1,COL2)
ON I.COL1 = s.COL1
WHEN MATCHED THEN

You could also reference this: "Merge" style operation with literal values?

Comments