如何回滚SQL Server中一次插入3个表中的数据

时间:2019-06-12 14:07:17

标签: sql-server tsql

我有3个表,我正在更新并将其插入所有这些表。

我的要求是,如果我们在表2或表3中遇到任何错误,我需要回滚所有表中所有插入和更新的数据。

如果所有插入和更新都成功,那么我们需要一次提交所有表。

表1:

UPDATE table1
SET Name = 'A'
WHERE Id =1

INSERT INTO Table1
    SELECT *  
    FROM Table

表2:

UPDATE table2 
SET Name = 'A'
WHERE Id =1

INSERT INTO Table2
    SELECT * 
    FROM Table

表3:

UPDATE table3 
SET Name = 'A'
WHERE Id =1

INSERT INTO Table3
    SELECT * 
    FROM Table

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

使用TRY...CATCH和交易:

--Begin the TRY
BEGIN TRY

    --Start a transaction    
    BEGIN TRANSACTION MyTran; --Might want a better name

    --Do all the operations    
    UPDATE table1
    SET Name = 'A'
    WHERE Id = 1;

    INSERT INTO Table1
    SELECT *
    FROM [Table];

    UPDATE table2
    SET Name = 'A'
    WHERE Id = 1;

    INSERT INTO Table2
    SELECT *
    FROM [Table];

    UPDATE table3
    SET Name = 'A'
    WHERE Id = 1;

    INSERT INTO Table3
    SELECT *
    FROM [Table];

    --All successful, so COMMIT
    COMMIT TRANSACTION MyTran;
END TRY
BEGIN CATCH

    --Roll back everything on failure
    ROLLBACK TRANSACTION MyTran;
    THROW;

END CATCH;