Last active
June 24, 2024 19:52
-
-
Save cemerson/dd3e9da12bdf0db4cad40fcdc12f7a56 to your computer and use it in GitHub Desktop.
TSQL: Template for transaction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BEGIN TRY | |
-- Start a transaction | |
BEGIN TRANSACTION; | |
-- Your T-SQL statements go here | |
-- Example: | |
----- YOUR SQL WORK HERE | |
-- If everything is successful, commit the transaction | |
ROLLBACK TRANSACTION; -- COMMIT when ready/stable | |
END TRY | |
BEGIN CATCH | |
-- An error occurred, roll back the transaction | |
IF @@TRANCOUNT > 0 | |
BEGIN | |
ROLLBACK TRANSACTION; | |
END | |
-- Log or re-throw the error | |
DECLARE @ErrorMessage NVARCHAR(4000); | |
DECLARE @ErrorSeverity INT; | |
DECLARE @ErrorState INT; | |
SELECT | |
@ErrorMessage = ERROR_MESSAGE(), | |
@ErrorSeverity = ERROR_SEVERITY(), | |
@ErrorState = ERROR_STATE(); | |
-- Optionally, log the error message somewhere or raise an error | |
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState); | |
END CATCH; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment