合并语句有两个插入?

时间:2013-07-13 14:56:21

标签: sql sql-server

给出一个简单的MERGE语句。我将记录插入/更新到traget表的位置。问题:是否可以将这些值插入到另一个表中,标志为0表示插入,1表示更新?例如。当不匹配时,插入目标和另一个表,匹配时更新目标并插入另一个表。

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
  --and insert into test_tbl values (1, Source.ProductID, Source.CustomerID) --?
WHEN NOT MATCHED BY TARGET THEN
  INSERT (CustomerID, ProductID, LastPurchaseDate)
  VALUES (Source.CustomerID, Source.ProductID, Source.PurchaseDate)
  --and insert into test_tbl values (0, Source.ProductID, Source.CustomerID) --?

1 个答案:

答案 0 :(得分:0)

你应该阅读OUTPUT

ex(source);

DECLARE @MergeOutput1 table
(
  ActionType nvarchar(10),
  BookID int,
  OldBookTitle nvarchar(50),
  NewBookTitle nvarchar(50),
  ModifiedDate datetime
);

-- use MERGE statement to perform update on Book2

MERGE Books2 AS b2
USING Books AS b1
ON (b2.BookID = b1.BookID)
WHEN MATCHED
THEN UPDATE
SET b2.BookTitle = b1.BookTitle
OUTPUT
    $action,
    INSERTED.BookID,
    DELETED.BookTitle,
    INSERTED.BookTitle,
    INSERTED.ModifiedDate
  INTO @MergeOutput1;