回滚触发器中的所有事务

时间:2015-06-26 03:54:08

标签: sql-server stored-procedures triggers

我需要在触发器中调用一个过程,这将调用另外几个跨国过程。如果任何过程失败,如何确保所有事务都回滚。谢谢

CREATE PROCEDURE dbo.PROC2(@pi_row INT)
AS
 BEGIN
  UPDATE TABLE abc SET col1 = @pi_row
 END 
GO

CREATE PROCEDURE dbo.PROC1(@pi_row INT)
AS
 BEGIN
  UPDATE TABLE xyz SET col1 = @pi_row
  EXEC dbo.PROC1 @pi_row
 END 
GO

CREATE TRIGGER test_insert ON xyz
    FOR INSERT
AS
  BEGIN
     DECLARE @pi_row int;

     SELECT @pi_row = rownumber
     FROM deleted;

     EXEC dbo.proc1 @pi_row;
  END; 
GO 

1 个答案:

答案 0 :(得分:2)

这可能有帮助: -

CREATE PROCEDURE dbo.PROC2(@pi_row INT)
AS
BEGIN
    UPDATE TABLE abc SET col1 = @pi_row
END 
GO

CREATE PROCEDURE dbo.PROC1(@pi_row INT)
AS
BEGIN

    Declare @TransName Varchar(100) = 'PIRowUpdation'

    Begin Tran @TransName

    UPDATE TABLE xyz SET col1 = @pi_row
    If @@Error <> 0 Goto Error

    EXEC dbo.PROC2 @pi_row
    If @@Error <> 0 Goto Error

    Commit Tran @TransName
    Goto LevelEnd

Error:
    Rollback Tran @TransName

LevelEnd:


END 
GO