没有源表的SQL Server MERGE

时间:2016-11-08 04:53:18

标签: sql sql-server merge

我正在学习如何使用此页面中的SQL Server MERGE语句: 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.*;

然而,我能找到的所有例子(例如上面的例子)都使用实际的表作为Source。是否可以直接传递数据?我宁愿不为此创建一个临时表(如果可能并建议?) 如何修改上述查询?

谢谢

3 个答案:

答案 0 :(得分:11)

请尝试以下格式:

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

您也可以参考: "Merge" style operation with literal values?

答案 1 :(得分:1)

你可以这样做:

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.*;

答案 2 :(得分:0)

我需要一个更简单的版本,并提出以下解决方案:

MERGE Target_Table
USING (VALUES (0)) as s(x)
ON last_run is not null
WHEN not matched then
insert (last_run) values(getdate())
when matched then
update set last_run=getDate();