TSQL: Try-Catch Transaction in Trigger

后端 未结 9 1645
长发绾君心
长发绾君心 2020-12-05 08:09

I am trying to put a try-catch statement inside a trigger using Microsoft Server 2005.

BEGIN TRANSACTION
BEGIN TRY
    --Some More SQL
    COMMIT TRANSACTION         


        
相关标签:
9条回答
  • 2020-12-05 08:45

    Isn't the best way but it works. Start a new transaction and do the normal commit rollback and begin another transaction in the end for implicit transaction commit

    http://msdn.microsoft.com/en-us/library/ms187844(v=SQL.90).aspx

    0 讨论(0)
  • 2020-12-05 08:48

    This demo achieves many of the things asked above. Error messages become optional. The trick that makes it work is in a the nested dynamic execute.

        if object_id('toto')  is not  null drop table toto
        go
        create table toto (i int);
        go
        if object_id('toto2')  is not  null drop table toto2
        go
        create table toto2 (i int);
        go
        create Trigger trtoto
        ON toto
        Instead Of Insert
        as
        Begin
          BEGIN TRY
            set nocount  on
            insert into  toto  values(2)
    
            declare @sql nvarchar(max) =  'insert into toto2 values(3); select * from ThisTableDoesntexist'
    
            Exec sp_executeSql N'set xact_abort off; exec (@sql) ', N'@sql nvarchar(max)', @sql
    
          END TRY
    
          BEGIN CATCH
            PRINT  'Error on line ' + CAST(ERROR_LINE() AS VARCHAR(10))
            PRINT ERROR_MESSAGE()
          END CATCH
        End
    
    GO
    -- tests
    set nocount on
    insert into toto values (1)  -- is not inserted on purpose by  the trigger
    select * from toto   -- other value inserted despite the error
    select * from toto2  -- other value inserted in other table despite the error
    
    0 讨论(0)
  • 2020-12-05 08:50

    Use SET XACT_ABORT OFF .When Transact-SQL statement encounter error ,it just raised the error message and the transaction continues processing. The following code is to create the trigger:

    Create TRIGGER [dbo].tr_Ins_Table_Master ON [dbo].Table_Master
     AFTER INSERT
    AS
    BEGIN
    set xact_abort off
    BEGIN TRY
            --your SQL          
            INSERT INTO Table_Detail
            SELECT MasterID,Name FROM INSERTED
    
    END TRY
    
    BEGIN CATCH     
        select ERROR_MESSAGE()
    END CATCH
    
    END
    
    0 讨论(0)
提交回复
热议问题