简体   繁体   English

SQL 合并到多个语句

[英]SQL Merge Into with multiple statements

I'm trying to keep a historic table of another one.我正在尝试保留另一个历史表。 When updating the original I would like to insert rows into the historic one.更新原始数据时,我想将行插入到历史数据中。 I'm using Sql Merge:我正在使用 Sql 合并:

MERGE TargetProducts AS Target
USING SourceProducts    AS Source
ON Source.ProductID = Target.ProductID
    
-- For Inserts
WHEN NOT MATCHED BY Target THEN
    INSERT (ProductID,ProductName, Price) 
    VALUES (Source.ProductID,Source.ProductName, Source.Price)
    
-- For Updates
WHEN MATCHED THEN UPDATE SET
    Target.ProductName  = Source.ProductName,
    Target.Price        = Source.Price
    
-- For Deletes
WHEN NOT MATCHED BY Source THEN
    DELETE;

Can I make multiple statements in the same " when " condition?, as such:我可以在同一个“ when ”条件下进行多条语句吗?例如:

...
-- For Inserts
WHEN NOT MATCHED BY Target THEN
    INSERT (ProductID,ProductName, Price) VALUES (Source.ProductID,Source.ProductName, Source.Price);
    INSERT INTO anotherTable (OldProductID,OldProductName, OldPrice) VALUES (Source.ProductID,Source.ProductName, Source.Price);
...

Normally you can INSERT only into one table.通常您只能INSERT到一张表中。 The syntax does not allow multiple statements in the same "when" condition.该语法不允许在同一个“when”条件下使用多个语句。

But, SQL Server has OUTPUT clause which allows to add another table.但是,SQL 服务器有OUTPUT子句允许添加另一个表。 It is very handy when you need to have some sort of auditing trail.当您需要某种审计跟踪时,它非常方便。

See this question How to INSERT into multiple tables from one SELECT statement看到这个问题How to INSERT into multiple tables from a SELECT statement

So, add OUTPUT clause to your MERGE statement.因此,将OUTPUT子句添加到您的MERGE语句中。 Something like this:像这样的东西:

MERGE TargetProducts AS Target
USING SourceProducts    AS Source
ON Source.ProductID = Target.ProductID
    
-- For Inserts
WHEN NOT MATCHED BY Target THEN
    INSERT (ProductID,ProductName, Price) 
    VALUES (Source.ProductID,Source.ProductName, Source.Price)
    
-- For Updates
WHEN MATCHED THEN UPDATE SET
    Target.ProductName  = Source.ProductName,
    Target.Price        = Source.Price
    
-- For Deletes
WHEN NOT MATCHED BY Source THEN
    DELETE

OUTPUT inserted.ProductID, inserted.ProductName, inserted.Price
INTO anotherTable (OldProductID,OldProductName, OldPrice)
;

This will capture both updates and inserts in anotherTable .这将捕获anotherTable中的更新和插入。 To capture only inserts you can output at first into a temp table and then filter results by MERGE $action .要仅捕获插入,您可以首先将 output 放入临时表中,然后通过 MERGE $action过滤结果。

Have a look at this question:看看这个问题:

Pipes and filters at DBMS-level: Splitting the MERGE output stream DBMS 级别的管道和过滤器:拆分 MERGE output stream

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

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