Try-Catch 在触发器内部没有按预期工作
Try-Catch does not work as expected inside the trigger
我在从 Trigger
调用的过程中得到了以下 T-sql
。 trigger
本身在另一个过程中得到 运行 并包装在 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
问题是,当 @MailProfileName
是一个 invalid
配置文件值时,sp_send_dbmail
引发了一个错误,到现在为止还不错,但是我对 try-catch
就是在 catch
块中捕获这个错误并抑制它,让执行在下一行继续。但是由于这个错误,整个过程实际上发生了崩溃。
有谁知道为什么会这样。
Ta.
回答 "why it happens" 的具体问题,当 xact_abort 开启时,错误导致整个事务(包括 try..catch 块)回滚,并且错误被抛出。
更新:
经过一番搜索后,我想到了这个解决方案:
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
但注意不要到处使用该变量。
我在从 Trigger
调用的过程中得到了以下 T-sql
。 trigger
本身在另一个过程中得到 运行 并包装在 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
问题是,当 @MailProfileName
是一个 invalid
配置文件值时,sp_send_dbmail
引发了一个错误,到现在为止还不错,但是我对 try-catch
就是在 catch
块中捕获这个错误并抑制它,让执行在下一行继续。但是由于这个错误,整个过程实际上发生了崩溃。
有谁知道为什么会这样。 Ta.
回答 "why it happens" 的具体问题,当 xact_abort 开启时,错误导致整个事务(包括 try..catch 块)回滚,并且错误被抛出。
更新: 经过一番搜索后,我想到了这个解决方案:
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
但注意不要到处使用该变量。