Skip to content

Instantly share code, notes, and snippets.

@hendrasyp
Created December 23, 2022 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrasyp/6d7fd7d91db51c0b26bd30903b179e65 to your computer and use it in GitHub Desktop.
Save hendrasyp/6d7fd7d91db51c0b26bd30903b179e65 to your computer and use it in GitHub Desktop.
SQL Server - Stored Procedure With Transaction
CREATE PROCEDURE [Schema].[SP_Name] (@Param [DataType(Size)] = DEFAULT_VALUE)
AS
BEGIN TRY
BEGIN TRANSACTION
-- Business Logic Here
-- Throw Exception Example
-- RAISERROR (N'Please delete detail vital sign first !!' , 11, 1);
-- RETURN;
COMMIT TRANSACTION
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE()
,@ErrorSeverity = ERROR_SEVERITY()
,@ErrorState = ERROR_STATE();
IF XACT_STATE() <> 0 BEGIN
ROLLBACK TRANSACTION
END
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment