语法:
MERGE
[ INTO ] <target_table> [ [ AS ] table_alias ]
USING <table_source> [ [ AS ] table_alias ]
ON <merge_search_condition>
[ WHEN MATCHED [ AND <clause_search_condition> ]
THEN <merge_matched> ] [ ...n ]
[ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]
THEN <merge_not_matched> ]
[ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
THEN <merge_matched> ] [ ...n ]
先建立一张新表
1 CREATE TABLE Sales.LastCustomerOrder 2 ( 3 CustomerID INT, 4 SalesOrderID INT, 5 CONSTRAINT pk_LastCustomerOrder PRIMARY KEY CLUSTERED (CustomerId) 6 ) ;
下面检查一行数据,由于目标表没有改记录,那么直接插入改记录
1 DECLARE @CustomerID INT = 100, 2 @SalesOrderID INT = 101 ; 3 4 MERGE INTO Sales.LastCustomerOrder AS tgt 5 USING 6 (SELECT @CustomerID AS CustomerID, 7 @SalesOrderID AS SalesOrderID 8 ) AS src 9 ON tgt.CustomerID = src.CustomerID 10 WHEN MATCHED 11 THEN UPDATE 12 SET SalesOrderID = src.SalesOrderID 13 WHEN NOT MATCHED 14 THEN INSERT ( 15 CustomerID, 16 SalesOrderID 17 ) 18 VALUES (src.CustomerID, 19 src.SalesOrderID) ;
结果
再将下面测试数据带入merge 语句
然后结果
再建立一张表,多加一个字段 money ,用于存储订单最大钱数,如果后续来自 source 订单的钱数大于当前订单,更新数据,否则不更新,当然没有的数据要添加
1 CREATE TABLE Sales.LargestCustomerOrder 2 ( 3 CustomerID INT, 4 SalesOrderID INT, 5 TotalDue MONEY, 6 CONSTRAINT pk_LargestCustomerOrder PRIMARY KEY CLUSTERED (CustomerId) 7 );
merge 语句
1 DECLARE @CustomerID INT = 100, 2 @SalesOrderID INT = 101 , 3 @TotalDue MONEY = 1000.00; 4 MERGE INTO Sales.LargestCustomerOrder AS tgt 5 USING 6 (SELECT @CustomerID AS CustomerID, 7 @SalesOrderID AS SalesOrderID, 8 @TotalDue AS TotalDue 9 ) AS src 10 ON tgt.CustomerID = src.CustomerID 11 WHEN MATCHED AND tgt.TotalDue < src.TotalDue 12 THEN UPDATE 13 SET SalesOrderID = src.SalesOrderID 14 , TotalDue = src.TotalDue 15 WHEN NOT MATCHED 16 THEN INSERT ( 17 CustomerID, 18 SalesOrderID, 19 TotalDue 20 ) 21 VALUES (src.CustomerID, 22 src.SalesOrderID, 23 src.TotalDue);
选择 matched 的顺序很重要,下面的情况会执行第一个为true 的分支
1 WHEN MATCHED AND tgt.TotalDue < src.TotalDue 2 THEN UPDATE 3 SET SalesOrderID = src.SalesOrderID 4 , TotalDue = src.TotalDue 5 WHEN MATCHED 6 THEN UPDATE 7 SET SalesOrderID = src.SalesOrderID
针对每一条记录操作的详细信息,下面的语句将会显示 执行的操作的统计信息
1 DECLARE @CustomerID INT = 100, 2 @SalesOrderID INT = 201 , 3 @TotalDue MONEY = 1200.00; 4 MERGE INTO Sales.LargestCustomerOrder AS tgt 5 USING 6 (SELECT @CustomerID AS CustomerID, 7 @SalesOrderID AS SalesOrderID, 8 @TotalDue AS TotalDue 9 ) AS src 10 ON tgt.CustomerID = src.CustomerID 11 WHEN MATCHED AND tgt.TotalDue < src.TotalDue 12 THEN UPDATE 13 SET SalesOrderID = src.SalesOrderID 14 , TotalDue = src.TotalDue 15 WHEN NOT MATCHED 16 THEN INSERT ( 17 CustomerID, 18 SalesOrderID, 19 TotalDue 20 ) 21 VALUES (src.CustomerID, 22 src.SalesOrderID, 23 src.TotalDue) 24 25 OUTPUT 26 $ACTION, 27 DELETED.*, 28 INSERTED.*;
结果