Try-Catch在触发器内不能按预期工作

时间:2015-04-22 05:09:01

标签: sql-server tsql exception-handling

我在T-sql调用的proc中找到了Triggertrigger本身在另一个proc中运行,并包含在transaction

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 :(得分: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

但请注意不要在任何地方使用该变量。