4

我想知道如果我不能插入,是否有办法回滚删除。

请指教。

像下面的东西。

BEGIN TRAN
Delete from MYTABLE where ID=@ID;

INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME

COMMIT
4

4 回答 4

10

您可以将两个语句放入一个TRY....CATCH块中,并且仅在两个语句都成功时才提交:

BEGIN TRANSACTION
BEGIN TRY
    DELETE FROM dbo.MYTABLE WHERE ID=@ID;

    INSERT INTO dbo.MYTABLE (ID, NAME)
       SELECT @ID, NAME

    -- COMMIT only if both DELETE and INSERT worked ....
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage

    -- ROLLBACK if either DELETE and INSERT failed ....
    ROLLBACK TRANSACTION
END CATCH
于 2013-04-01T16:27:57.020 回答
3

打开xact_abort以在出现任何错误时回滚事务。

SET XACT_ABORT ON;
BEGIN TRAN
Delete from MYTABLE where ID=@ID;

INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME

COMMIT TRAN
于 2013-04-01T18:17:42.413 回答
0

这是完成您似乎正在尝试的另一种方法:

update myTable
set name = @name
where id = @id
于 2013-04-01T16:36:37.233 回答
0
BEGIN TRAN

Delete from MYTABLE where ID=@ID;

INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME

if @@error = 0 and @@trancount > 0
    commit
else
    rollback
于 2013-04-01T17:58:09.260 回答