@@ERROR 和/或 TRY - CATCH [英] @@ERROR and/or TRY - CATCH
问题描述
Try-Catch 会捕获@@ERROR 可以捕获的所有错误吗?在下面的代码片段中,是否值得检查@@ERROR?RETURN 1111 会发生吗?
Will Try-Catch capture all errors that @@ERROR can? In the following code fragment, is it worthwhile to check for @@ERROR? Will RETURN 1111 ever occur?
SET XACT_ABORT ON
BEGIN TRANSACTION
BEGIN TRY
--do sql command here <<<<<<<<<<<
SELECT @Error=@@ERROR
IF @Error!=0
BEGIN
IF XACT_STATE()!=0
BEGIN
ROLLBACK TRANSACTION
END
RETURN 1111
END
END TRY
BEGIN CATCH
IF XACT_STATE()!=0
BEGIN
ROLLBACK TRANSACTION
END
RETURN 2222
END CATCH
IF XACT_STATE()=1
BEGIN
COMMIT
END
RETURN 0
推荐答案
以下文章是 SQL Server MVP Erland Sommarskog 的必读文章:使用存储过程实现错误处理
The following article is a must read by Erland Sommarskog, SQL Server MVP: Implementing Error Handling with Stored Procedures
另请注意您的 TRY 块可能会失败,您的 CATCH 块可能会被绕过
还有一件事:使用旧式错误处理和保存点的存储过程在与 TRY … CATCH 块一起使用时可能无法按预期工作.避免混合新旧错误处理方式.
One more thing: Stored procedures using old-style error handling and savepoints may not work as intended when they are used together with TRY … CATCH blocks.Avoid mixing old and new styles of error handling.
这篇关于@@ERROR 和/或 TRY - CATCH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!