Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 965
RockScience Avatar asked Nov 08 '16 04:11

RockScience


People also ask

How do I MERGE tables in SQL Server?

First, you specify the target table and the source table in the MERGE clause. Second, the merge_condition determines how the rows from the source table are matched to the rows from the target table. It is similar to the join condition in the join clause.

Which of the following rules of using SQL MERGE is not applicable?

We cannot use WHEN NOT MATCHED BY SOURCE clause more than two times. If WHEN NOT MATCHED BY SOURCE clause in SQL Server MERGE statement was specified two times, one must use an update operation and another one must use delete operation.


1 Answers

You could do it like this:

Declare @customerID int = 1;
Declare @productID int = 1;
Declare @purchaseDate date = '1900-01-01';

MERGE dbo.FactBuyingHabits AS Target
USING (SELECT CustomerID = @customerID, 
    ProductID = @productID, 
    PurchaseDate = @purchaseDate) 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.*;
like image 83
mendosi Avatar answered Oct 10 '22 15:10

mendosi