我在回滚时将MERGE语句包装在事务中并检查输出。语句也可以是CTE的最后一部分。您可以在具有不同子句的 a 中包含多个,和语句。MERGE
UPDATE
INSERT
DELETE
MERGE
WHERE
注意:在合并语句中,连接中的每个列不能有多行。
代码:
SET XACT_ABORT ON --When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
BEGIN TRANSACTION;
MERGE Table1 AS T
USING Table2 AS S
ON --<< Update the join to the correct unique key for the table (can't have duplicate rows)
T.[col1] = S.[col1]
AND T.[col2] = S.[col2]
AND T.[col3] = S.[col3]
WHEN NOT MATCHED BY TARGET -- AND 1=2 --<< you can include a where clause here
THEN INSERT
(
[col1], [col2], [col3]
)
VALUES
(
S.[col1], S.[col2], S.[col3]
)
WHEN MATCHED -- AND 1=2 --<< you can include a where clause here
THEN UPDATE SET
T.[col1] = S.[col1]
, T.[col2] = S.[col2]
, T.[col3] = S.[col3]
--WHEN NOT MATCHED BY SOURCE -- AND 1=2 --<< you can include a where clause here
--THEN DELETE
OUTPUT @@SERVERNAME AS [Server_Name], DB_NAME() AS [Database_Name], $action, inserted.*, deleted.*;
ROLLBACK TRANSACTION;
--COMMIT TRANSACTION;
GO