The following example uses MERGE to update or insert rows to modify the SalesReason table. When the NewName value in the source table matches the value in the Name column of the target table (SalesReason), The ReasonType column in the target table is updated. When the value of NewName does not match, the source row is inserted into the target table. This source table is a school
The following example uses MERGE to update or insert rows to modify the SalesReason table. When the NewName value in the source table matches the value in the Name column of the target table (SalesReason), The ReasonType column in the target table is updated. When the value of NewName does not match, the source row is inserted into the target table. This source table is a school
The following example uses MERGE to update or insert rows to modify the SalesReason table. When the NewName value in the source table matches the value in the Name column of the target table (SalesReason), The ReasonType column in the target table is updated. When the value of NewName does not match, the source row is inserted into the target table. This source table is a derived table. It uses the Transact-SQL Table value constructor to specify multiple rows in the source table. For more information about using Table value constructor in a derived table, see Table value Constructor (Transact-SQL ). This example also shows how to store OUTPUT clause results in Table variables, it also describes how to summarize the results of the MERGE Statement by executing a simple selection operation to return the counts of inserted and updated rows. <无>
USE AdventureWorks2012;GO-- Create a temporary table variable to hold the output actions.DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20));MERGE INTO Sales.SalesReason AS TargetUSING (VALUES ('Recommendation','Other'), ('Review', 'Marketing'), ('Internet', 'Promotion')) AS Source (NewName, NewReasonType)ON Target.Name = Source.NewNameWHEN MATCHED THENUPDATE SET ReasonType = Source.NewReasonTypeWHEN NOT MATCHED BY TARGET THENINSERT (Name, ReasonType) VALUES (NewName, NewReasonType)OUTPUT $action INTO @SummaryOfChanges;-- Query the results of the table variable.SELECT Change, COUNT(1) AS CountPerChangeFROM @SummaryOfChangesGROUP BY Change;