2015-04-22 44 views
1

我在Trigger的调用过程中得到了以下的T-sqltrigger本身在另一个proc中运行,并被包装在transaction中。Try-Catch在触发器内不能正常工作

IF @Email <> '' 
BEGIN 
    BEGIN TRY 
    EXEC msdb..sp_send_dbmail 
     @profile_name = @MailProfileName, 
     @recipients = @Email, 
     @subject = @Subject, 
     @body = @EmailBody, 
     @body_format = @EmailBodyFormat 
    END TRY 
    BEGIN CATCH 
    -- In future this error can be logged to message log or as an action message but ignore for now, it's due to mail profile setting. 
    --SELECT ERROR_MESSAGE() 
    END CATCH 
END 

的问题是,当@MailProfileNameinvalid曲线值,则sp_send_dbmail引发的错误是罚款到现在为止,但后来我从try-catch想到的是赶上这个错误在catch块压制它并让执行继续下一行。但是,由于这个错误,整个过程实际上发生了什么事情。

有没有人有任何想法为什么会发生。 Ta。

+1

请避免编辑问题以包含解决方案。相反,回答你自己的问题并接受答案,以便人们知道问题已经解决。 –

回答

0

更新: 我想出了这个解决方案有点搜索后:

IF @Email <> '' 
BEGIN 
    BEGIN TRY 
    Set xact_abort off 
    EXEC msdb..sp_send_dbmail 
     @profile_name = @MailProfileName, 
     @recipients = @Email, 
     @subject = @Subject, 
     @body = @EmailBody, 
     @body_format = @EmailBodyFormat 
    Set xact_abort on 
    END TRY 
    BEGIN CATCH 
    -- In future this error can be logged to message log or as an action message but ignore for now, it's due to mail profile setting. 

    --SELECT ERROR_MESSAGE() 
    END CATCH 
END 

但要小心,不要使用变量无处不在。

0

要回答“为什么会发生”的具体问题,当xact_abort打开时,错误会导致包含try..catch块的整个事务回滚,并引发错误。