使用SQL Server中的MERGE同时插入、更新和删除

MERGE [AS TARGET] 
  USING [AS SOURCE]

  ON (TARGET.CodeID = SOURCE.CodeID)
   
    --When records are matched, update
    --the records if there is any change
  [WHEN MATCHED THEN ]
    UPDATE SET TARGET.TaxCode = SOURCE.TaxCode;
 
   --When no records are matched, insert
   --the incoming records from source
   --table to target table
  [WHEN NOT MATCHED [BY TARGET] THEN ]
   INSERT ......
 
    --When there is a row that exists in target table and
   --same record does not exist in source table
   --then delete this record from target table
  [WHEN NOT MATCHED BY SOURCE THEN ];
    DELETE
 

OUTPUT $action,

   DELETED.CodeID AS TargetCodeID,
   DELETED.TaxCode AS TargetTaxCode,
   DELETED.AppendCode AS TargetAppendCode,
   DELETED.CodeName AS TargetCodeName,
   INSERTED.CodeID AS SourceCodeID,
   INSERTED.TaxCode AS SourceTaxCode,
   INSERTED.AppendCode AS SourceAppendCode,
   INSERTED.CodeName AS SourceCodeName;

(要以分号结束)
select @@ROWCOUNT;
原文地址:https://www.cnblogs.com/yourancao520/p/2335635.html