Best Practice for Writing SQL Server Stored Procedure with Transaction -
- Enclose withing
TRY..CATCH
block
- Check for
@@TRANCOUNT
and ROLLBACK
Transaction on ERROR
RAISE
actual ERROR
to alarm calling program
Sample -
CREATE PROCEDURE [dbo].[ReAdmissionInsert]
@GRNo varchar(4),
@ClassId numeric(2),
@FacultyId numeric(1),
@Section varchar(1),
@SessionId numeric(1)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
BEGIN TRAN
insert into ReAdmissionDtl(GRNo,ClassId,FacultyId,Section,SessionId)
values(@GRNo,@ClassId,@FacultyId,@Section,@SessionId)
delete from Discharge where GRNo = @GRNo
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
/*ERROR OCCURED*/
DECLARE @ERROR_MESSAGE NVARCHAR(4000);--MESSAGE TEXT
DECLARE @ERROR_SEVERITY INT;--SEVERITY
DECLARE @ERROR_STATE INT;--STATE
SELECT @ERROR_MESSAGE = ERROR_MESSAGE(),
@ERROR_SEVERITY = ERROR_SEVERITY(),
@ERROR_STATE = ERROR_STATE()
/*RETURN ERROR INFORMATION ABOUT THE ORIGINAL ERROR THAT CAUSED
EXECUTION TO JUMP TO THE CATCH BLOCK.*/
RAISERROR (@ERROR_MESSAGE, @ERROR_SEVERITY, @ERROR_STATE)
END CATCH
END
Notice that @@TRANCOUNT
is checked to verify if there is any open transactions and ERROR
messages are retained and raised so program will receive SqlException
.