I'm trying to implement some simple error handling into my (simple) proc and have been advised to use the @@TRANCOUNT method.
My code is as below:
ALTER PROCEDURE [dbo].[spTestSystem1]
@ErrorCode int OUTPUT
AS
BEGIN TRAN
BEGIN TRY
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
INSERT INTO tblTestSystem1
([Date],
[Field1],
[Field2])
(SELECT [Date],
[Field3],
[Field4])
FROM vwAnotherView)
END TRY
BEGIN CATCH
IF @@TRANCOUNT >0
BEGIN
PRINT @@TRANCOUNT
ROLLBACK TRAN
SET @ErrorCode=1
PRINT @ErrorCode
END
END CATCH
IF @@TRANCOUNT >0
BEGIN
COMMIT TRAN
PRINT @@TRANCOUNT
SET @ErrorCode=0
PRINT @ErrorCode
END
Normally it runs fine but I need to break it to make sure that the trapping is working OK.
To do that I renamed the View in my system and then re-ran it.
The first error I got was expected:
"Invalid object name"
However the second error has confused me:
"Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing."
Is this the best way of implementing error handling in a simple proc?
My code is as below:
ALTER PROCEDURE [dbo].[spTestSystem1]
@ErrorCode int OUTPUT
AS
BEGIN TRAN
BEGIN TRY
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
INSERT INTO tblTestSystem1
([Date],
[Field1],
[Field2])
(SELECT [Date],
[Field3],
[Field4])
FROM vwAnotherView)
END TRY
BEGIN CATCH
IF @@TRANCOUNT >0
BEGIN
PRINT @@TRANCOUNT
ROLLBACK TRAN
SET @ErrorCode=1
PRINT @ErrorCode
END
END CATCH
IF @@TRANCOUNT >0
BEGIN
COMMIT TRAN
PRINT @@TRANCOUNT
SET @ErrorCode=0
PRINT @ErrorCode
END
Normally it runs fine but I need to break it to make sure that the trapping is working OK.
To do that I renamed the View in my system and then re-ran it.
The first error I got was expected:
"Invalid object name"
However the second error has confused me:
"Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing."
Is this the best way of implementing error handling in a simple proc?