2. 创建事务和结束事务的时候最好有这样的判断:
IF @@TRANCOUNT = 0
BEGIN -- only if @@TRANCOUNT is 0, we do BEGIN TRAN
BEGIN TRANSACTION
SET @TransactionIsOurs = 1
END
IF @TransactionIsOurs = 1
BEGIN
COMMIT TRANSACTION
-- SET @TransactionIsOurs = 0
END
IF @TransactionIsOurs = 1 AND @@TRANCOUNT > 0
ROLLBACK TRANSACTION
3. 如果事务很长,可以在适当的位置多加几个错误判断:
Code
Note:@@Error必须直接跟在需要判断的sql后面,中间不能间隔其他语句,因为@@Error总是取最新执行的结果,所以最好还是使用Try...Catch...
USE AdventureWorks;
GO
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