Я обертываю свои MERGE операторы в транзакции при откате и проверяю вывод.Оператор MERGE
также может быть последней частью CTE .Вы можете иметь несколько операторов 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