Last active
December 20, 2022 19:00
-
-
Save mishrsud/73a48873907a437d9cf3 to your computer and use it in GitHub Desktop.
SQL TRY-CATCH WITH 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
SET ANSI_NULLS ON | |
GO | |
SET QUOTED_IDENTIFIER ON | |
GO | |
CREATE PROC [dbo].[pr_ins_test] | |
@CompanyID INT | |
AS | |
SET NOCOUNT ON | |
BEGIN | |
DECLARE @PreviousConfigID INT | |
BEGIN TRY | |
BEGIN TRANSACTION MYTRAN; -- Give the transaction a name | |
SELECT 1/0 -- Generates divide by zero error causing control to jump into catch | |
PRINT '>> COMMITING' | |
COMMIT TRANSACTION MYTRAN; | |
END TRY | |
BEGIN CATCH | |
IF @@TRANCOUNT > 0 | |
BEGIN | |
PRINT '>> ROLLING BACK' | |
ROLLBACK TRANSACTION MYTRAN; | |
THROW | |
END | |
END CATCH | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment