Skip to content

Instantly share code, notes, and snippets.

@mishrsud
Last active December 20, 2022 19:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mishrsud/73a48873907a437d9cf3 to your computer and use it in GitHub Desktop.
Save mishrsud/73a48873907a437d9cf3 to your computer and use it in GitHub Desktop.
SQL TRY-CATCH WITH TRANSACTION
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