Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsql transaction

In order to wrap stored procedure in a transaction I add the following:

CREATE PROCEDURE [dbo].[P_ORD_InsertTextField]
    //PARAMS
AS
BEGIN
    BEGIN TRY
    BEGIN TRANSACTION

    //STP BODY

    COMMIT
    END TRY
    BEGIN CATCH
      IF @@TRANCOUNT > 0
         ROLLBACK

      DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
      SELECT @ErrMsg = ERROR_MESSAGE(),
             @ErrSeverity = ERROR_SEVERITY()

      RAISERROR(@ErrMsg, @ErrSeverity, 1)
    END CATCH
END
GO

Is there any shorter way that does the same? this is a huge code block for "just" handle a transaction..

like image 292
Naor Avatar asked Oct 11 '22 13:10

Naor


1 Answers

No, this is pretty much it.

You can hide the @ErrMsg processing behind a stored proc or UDF, and you don't need @ErrSeverity processing. It is normally 16 which is "user defined error"

See my answer here too please: Nested stored procedures containing TRY CATCH ROLLBACK pattern?

like image 126
gbn Avatar answered Oct 14 '22 10:10

gbn