⌘BABAKOV.NET Let's code!
100% [dark] [ru]

MSSQL - Try Catch Transaction (Canceling transaction with an error correctly)

Below is an example of correctly canceling a transaction with an error:

update Params set Value=168 where Param = \'SessionHoursLimit\'

PRINT @@TRANCOUNT  
	BEGIN TRY
    BEGIN TRAN  
        PRINT @@TRANCOUNT  
		update Params set Value=167 where Param = \'SessionHoursLimit\'
		select 1/0 -- Если закомментировать эту строку то предыдущая строка выполнится
    COMMIT  TRAN 
	END TRY
	BEGIN CATCH
		if @@TRANCOUNT>0
		ROLLBACK TRAN
	END CATCH
PRINT @@TRANCOUNT  

select * from Params



If you comment out the line with the erroneous operator SELECT 1/0 then the previous line will be executed and the transaction will be completed successfully, if you leave the line SELECT 1/0 then the transaction will be canceled completely, and the Value parameter will remain as it was set in the first line of the script before the transaction began.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.