我正在阅读MSDN上的TRY-CATCH
块示例。
示例B的代码清单如下:
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
我不明白的是为什么他们会费心去检查街区@@TRANCOUNT
。CATCH
在此代码段中,交易计数是否真的有可能 < 1,或者保护条款只是例子应该是示例原则的示例?
它是一种防御性编程实践,仅在可能的情况下执行操作(回滚)。
该表可能具有
DELETE
回滚事务并抛出错误的触发器。