哪种方式更好?
BEGIN TRAN
BEGIN TRY
-- Code here
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
或
BEGIN TRY
BEGIN TRAN
-- Code here
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
答案 0 :(得分:2)
交易不尊重TRY CATCH
边界。一旦遇到COMMIT或ROLLBACK,无论事务是在TRY块内部还是在其外部启动,事务都会关闭。
Best practice is to keep your transaction as short as posssible. With this rule, I will prefer 2nd approach.
很棒的文章@ MSDN ...摘要在这里
“..如果TRY块中生成的错误导致当前事务的状态无效,则该事务被归类为不可提交的事务。通常在TRY块之外结束事务的错误会导致事务在TRY块内发生错误时进入不可提交状态。不可提交的事务只能执行读操作或ROLLBACK TRANSACTION。事务不能执行任何会产生写操作或COMMIT TRANSACTION的Transact-SQL语句。 “
In your example 1. There is an issue
BEGIN TRAN
BEGIN TRY
-- Code here
END TRY
BEGIN CATCH
ROLLBACK
END CATCH
COMMIT
如果try块内发生异常,则事务将在catch块中回滚。在此步骤之后,COMMIT将触发一个异常,说明没有要提交的开放事务。
答案 1 :(得分:0)
BEGIN TRY
-- Do the obvious checks 1st if something isnt correct raise error and
-- get out of try block, A transaction will never begin
IF (Some Condition 1)
BEGIN
RAISERROR('Something gone Wrong',16,1)
END
IF (Some Condition 2)
BEGIN
RAISERROR('Something gone Wrong',16,1)
END
--if nothing has gone wrong ...
-- Now open a transaction
BEGIN TRANSACTION
-- Code here
COMMIT TRANSACTION --<-- If nothing goes wrong commit
END TRY
BEGIN CATCH
IF @@TRANCOUNT <> 0
BEGIN
ROLLBACK TRANSACTION
END
SELECT ERROR_LINE(),
ERROR_MESSAGE(),
..... Other Error fucntion to collect information
-- about error
END CATCH
当控件在TRY BLOCK
时如果一切顺利,即Sql server不会抛出错误或者你没有引发错误。控制权永远不会进入CATCH BLOCK
,因此您必须在TRY Block
内进行COMMIT交易。