I've prepare a template for SQL Server stored procedures which will have Insert, delete, Update transaction.
I have a stored procedure to log error in catch block in a table.
How can I improve my stored procedure to handle transactional error or any kind of error where stored procedure should not give error on screen.
- Can this be improved to handle transaction in proper way or it sufficient?
- First
Begin tran
block orBegin Try
block? - Rollback in
catch
blockif @@trancount > 0
sufficient? - Use of
Xact_abort on
in every Insert, delete, update transaction procedure is ok?
Code:
ALTER PROCEDURE [dbo].[DB_INSERT_MY_LOG]
(@Param1 varchar(30))
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @ErrNumber NVARCHAR(100)
,@ErrDescription NVARCHAR(4000)
,@ErrorProcedure NVARCHAR(200)
,@ErrState INT
,@ErrSeverity INT
,@ErrLine INT
,@ErrTime DATETIME
BEGIN TRAN
BEGIN TRY
--Insert or Update or Delete or (Insert & Update together and vice versa) & multiple insert into different tables.
COMMIT TRAN
END TRY
BEGIN CATCH
IF (@@TRANCOUNT > 0)
ROLLBACK TRAN
SET @ErrNumber = ERROR_NUMBER()
SET @ErrDescription = ERROR_MESSAGE()
SET @ErrorProcedure = ERROR_PROCEDURE()
SET @ErrState = ERROR_STATE()
SET @ErrSeverity = ERROR_SEVERITY()
SET @ErrLine = ERROR_LINE()
SET @ErrTime = GETDATE()
EXEC MyErrorLogInsert
@ErrorNumber = @ErrNumber
,@ErrorDescription = @ErrDescription
,@ErrorProcedure = 'DB_INSERT_MY_LOG'
,@ErrorState = @ErrState
,@ErrorSeverity = @ErrSeverity
,@ErrorLine = @ErrLine
,@ErrorTime = @ErrTime
END CATCH
SET NOCOUNT OFF;
SET XACT_ABORT OFF;