简体   繁体   English

没有源表的SQL Server MERGE

[英]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 我正在学习如何使用此页面中的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.*;

However all the examples I can find (such as the one above) are using an actual table as Source. 但是我可以找到的所有示例(例如上面的示例)都使用实际表作为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 谢谢

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? 您还可以参考: “合并”样式操作与文字值?

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

I needed an even simpler version and came to this solution: 我需要一个更简单的版本,并找到了这个解决方案:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM