问题描述
我有以下交易。如果点的总和不等于4000,我希望它回滚,如果它的积分是COMMIT,则它要回滚。我执行了交易,积分不等于4000。但是仍然执行了交易。为什么呢?
BEGIN TRAN [Whist]
BEGIN TRY
END TRY
BEGIN CATCH
IF (SELECT SUM(Point) FROM dbo.Players) <> 4000
ROLLBACK TRANSACTION [Whist]
END CATCH
IF (SELECT SUM(Point) FROM dbo.Players) = 4000
COMMIT TRAN
解决方法
请以2种方式运行此SQL。 @sum_of_points设置为4000后,将提交事务。第二次将@sum_of_points设置为4001,这将回滚事务。
BEGIN TRAN
BEGIN TRY
declare @sum_of_points int=4000;
IF (@sum_of_points <> 4000)
throw 50000,'Not equals 4000 so do not commit the transaction',1;
commit transaction;
print ('transaction was committed')
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
print ('transaction has been rolled back');
END CATCH