-1

I am trying to write logs for stored procedures. I am putting my sp in try block and trying to catch exceptions in catch block . If there are any exceptions I am ROLLING BACK the transaction or I am COMMITING the transaction.

USE [RPM_BROKER_TOOL]
GO
/****** Object:  StoredProcedure [dbo].[RPM_PROC_UPDATE_BROKER_SETTINGS]    Script Date: 09/24/2015 16:28:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- AUTHOR     : ROHIT NAIK
-- CREATE DATE: 31-JULY-2015
-- DESCRIPTION: Update Broker Tool settings.
-- =============================================
ALTER PROCEDURE [dbo].[RPM_PROC_UPDATE_BROKER_SETTINGS](
                        @pk_broker_param int,
                        @companyID int,
                        --@BrokerSetting xml
                        @broker_param_id int,
                        @fixed_param_id int,
                        @Exchange_Type varchar(10),
                        @Parameter_Description varchar(100),
                        @DataSize int,
                        @DataType varchar(2),
                        @DataValue varchar(100),
                        @Dialog_Filter varchar(100),
                        @ListOfValues varchar(500),
                        @isMandatory BIT,
                        @CREATED_IN_MODULE varchar(30),
                        @CREATE_LOGIN_NAME varchar(10),
                        @CREATED_ON DATETIME,
                        @Field_Type varchar(5),
                        @Updated_Login varchar(10),
                        @SequenceId int,
                        @Description varchar(1000)          
                        )

AS

DECLARE @Current_Timestamp DATETIME = current_timestamp,
        @RowsInserted int,
        @ErrorMessage varchar(1000),
        @ErrorTable RPM_EXCEPTION_TYPE_TEMP ,
        @ProcName varchar(100)
        --@IN_Pk_Broker_Param int used for auditing

DECLARE @ID_MODULE INT,@DATA_VALUE VARCHAR(500)
SET @ID_MODULE = (SELECT ID_MODULE FROM FW_MODULES WHERE CD_MODULE = 'BROKER APP')
SET @ProcName = (SELECT OBJECT_NAME(@@PROCID))
BEGIN

BEGIN TRY
    BEGIN TRANSACTION

SELECT @DATA_VALUE=DATAVALUE FROM RPM_BROKER_TOOL_CALIBRATION_PARAMETERS WHERE AUDIT_ACTIVE=1 AND FIXED_PARAMETER_ID=@fixed_param_id
IF ISNULL(@DATA_VALUE,'')<>@DataValue
BEGIN
        select 1/0
        INSERT INTO RPM_BROKER_TOOL_CALIBRATION_PARAMETERS(
                        ID_COMPANY,
                        --ID_BROKER_PARAM,
                        FIXED_PARAMETER_ID,
                        EXCHANGE_TYPE,
                        PARAMETER_DESCRIPTION,
                        DATASIZE,
                        DATATYPE,
                        DATAVALUE,
                        DAILOG_FILE_FILTER,
                        LOV,
                        isMandatory,
                        CREATED_IN_MODULE,
                        CREATE_LOGIN_NAME,
                        CREATE_TIME_STAMP,
                        UPDATED_IN_MODULE,
                        UPDATE_LOGIN_NAME,
                        UPDATE_TIME_STAMP,
                        AUDIT_ACTIVE,
                        AUDIT_TYPE,
                        AUDIT_FROM_DATE,
                        AUDIT_TO_DATE,                      
                        SESSION_ID,
                        Field_Type,
                        ID_SEQUENCE,
                        Description
                        )

                VALUES (                        
                        @companyID,
                        --@broker_param_id,
                        @fixed_param_id,
                        @Exchange_Type,
                        @Parameter_Description,
                        @DataSize,
                        @DataType,
                        @DataValue,
                        @Dialog_Filter,
                        @ListOfValues,
                        @isMandatory,
                        @CREATED_IN_MODULE,
                        @CREATE_LOGIN_NAME,
                        @CREATED_ON,
                        @CREATED_IN_MODULE,
                        @Updated_Login,
                        @Current_Timestamp,
                        1,
                        'E',
                        @Current_Timestamp,
                        '12/31/2099',
                        null,
                        @Field_Type,
                        @SequenceId,
                        @Description 
                        )
                    SET @RowsInserted = @@ROWCOUNT

                    SET @ErrorMessage = 'Number of rows updated: ' + convert(varchar(100),@RowsInserted) 
                INSERT INTO @ErrorTable (COMPANY_ID,ID_OBJECT,LOGIN_NAME,MODULE_CODE,PROC_NAME,TIME_STAMP,BUSSINESS_MODULE,EXCEPTION_CATEGORY,EXCEPTION_LEVEL,EXCEPTION_DESCRIPTION)
                VALUES (@companyID,NULL,@CREATE_LOGIN_NAME,@CREATED_IN_MODULE,@ProcName,@Current_Timestamp,NULL,'Information','Normal',@ErrorMessage)

                UPDATE  RPM_BROKER_TOOL_CALIBRATION_PARAMETERS
                SET     AUDIT_ACTIVE = 0, AUDIT_TO_DATE = @Current_Timestamp,
                        UPDATE_TIME_STAMP = @Current_Timestamp, 
                        UPDATE_LOGIN_NAME = @Updated_Login,
                        UPDATED_IN_MODULE = @CREATED_IN_MODULE
                WHERE   PK_BROKER_PARAM = @pk_broker_param


        declare @Update_fields varchar(200)
        set @Update_fields = @Parameter_Description + ' modified'

        EXEC RPM_PROC_INSERT_AUDIT 
        '4016'
        ,@companyID
        ,@pk_broker_param
        --,@fixed_param_id
        ,1 
        ,'E'
        ,@Parameter_Description
        ,@Update_fields
        ,@CREATED_IN_MODULE
        ,@Updated_Login
        ,'BROKER APP SETTINGS'
        ,@CURRENT_TIMESTAMP



END
    COMMIT TRANSACTION
END TRY

BEGIN CATCH

    SET @ErrorMessage = 'Error : ' + ERROR_MESSAGE() + 'on #Line ' + convert(varchar(1000),ERROR_LINE())

    INSERT INTO @ErrorTable (COMPANY_ID,ID_OBJECT,LOGIN_NAME,MODULE_CODE,PROC_NAME,TIME_STAMP,BUSSINESS_MODULE,EXCEPTION_CATEGORY,EXCEPTION_LEVEL,EXCEPTION_DESCRIPTION)
                VALUES (@companyID,NULL,@CREATE_LOGIN_NAME,@CREATED_IN_MODULE,@ProcName,@Current_Timestamp,NULL,'Error','High',@ErrorMessage)
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
END CATCH

    EXEC update_db_log @ErrorTable

END
ROY
  • 1
  • 4
  • Does your `RPM_PROC_INSERT_AUDIT` rollback transaction too? – Lukasz Szozda Sep 24 '15 at 11:37
  • Check with `XACT_STATE()` in `CATCH` block and handle appropriate aborted and uncommitable transactions. Anyways why you are using `SELECT 1/0` ? – Abhishek Sep 24 '15 at 11:39
  • I guess it will rollback your `INSERT INTO @ErrorTable ...` also – Sachin Sep 24 '15 at 11:41
  • @lad2025 No it doesn't – ROY Sep 24 '15 at 11:45
  • @Abhishek Actually I am using select 1/0 as a dummy exception – ROY Sep 24 '15 at 11:47
  • @Sac No it doesn't. data is inserted in error table. but RTE is thrown at fe – ROY Sep 24 '15 at 11:48
  • what's the question exactly? you are committing or rolling back? in the code you rollback: why you write ' I am ROLLING BACK the transaction or I am COMMITING the transaction' in the question? – Paolo Sep 24 '15 at 12:06
  • @Paolo If the exception is catched, the trans should rollback, else it should commit – ROY Sep 24 '15 at 12:24
  • So when you are executing the SP due to `SELECT 1/0` exception is raised and in `CATCH` block you are getting error? – Abhishek Sep 24 '15 at 12:33
  • @Abhishek the exception is catched in catch block, but an unwanted RTE ("Transaction count after execute indicates a mismatching number of begin and commit") is raised. Want to get rid of it – ROY Sep 24 '15 at 13:05
  • Could you print the `@@TRANCOUNT` in `TRY-CATCH` block to see what actually is happening. Also try commenting out the SP **RPM_PROC_INSERT_AUDIT** – Abhishek Sep 24 '15 at 13:16
  • @Abhishek I did as you said. Now before ROLLBACK it is showing TRANCOUNt -> 2 and after ROLLBACK -> 0 strange! – ROY Sep 25 '15 at 05:54
  • So your `BEGIN TRANSACTION` should increment `@@TRANCOUNT` by 1 and `COMMIT TRANSACTION` decrement `@@TRANCOUNT` by 1 otherwise in case of `exception` then `ROLLBACK TRANSACTION` will decrement `@@TRANCOUNT` to 0 which is not happening in your case. So suspecting the current transaction was called from another stored procedure which had its own transaction/or called an inner stored procedure which had its own transaction. So might be your inner SP **RPM_PROC_INSERT_AUDIT** should also have some `transaction` statements which are not handled properly. – Abhishek Sep 25 '15 at 13:21
  • @Abhishek The problem is solved. It was rather a sillly one :p. I had begin transaction and end transaction statements in my code. After commenting them everything is working fine ! Thanks :) – ROY Oct 01 '15 at 05:59

1 Answers1

0

I don't know why you are getting the issue. But when I have done exactly like your code, I got same Transaction Count. Here is my code:

CREATE TABLE

CREATE TABLE [dbo].[Test](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [IsActive] [bit] NULL CONSTRAINT [DF_Emails_IsActive]  DEFAULT ((1))
)

SQL

BEGIN TRY
    BEGIN TRANSACTION
        Print(@@TRANCOUNT)
        Print('start')
        Print(@@TRANCOUNT)
        INSERT INTO Test VALUES ('First')
        select 1/0
        Print(@@TRANCOUNT)
        Print('never reach')
        INSERT INTO Test VALUES ('Second')
        Print(@@TRANCOUNT)
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    Print(@@TRANCOUNT)
    Print('catch called')
    INSERT INTO Test VALUES ('Third')
    Print(@@TRANCOUNT)
    Print('inserted')

    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
END CATCH
SELECT * FROM Test 

And the statement before Rollback is also rolled back. (In your case, INSERT INTO @ErrorTable ... as per my comment. )

Here is the output:

1
start
1

(1 row(s) affected)

(0 row(s) affected)
1
catch called

(1 row(s) affected)
1
inserted

(0 row(s) affected)
Sachin
  • 2,152
  • 1
  • 21
  • 43
  • Yes. but the code throws RTE at fe "Transaction count after execute indicates a mismatching number of begin and commit" – ROY Sep 24 '15 at 12:28
  • Have you read and check this : http://stackoverflow.com/a/21930372/1659563 Try by commenting `EXEC RPM_PROC_INSERT_AUDIT...` – Sachin Sep 24 '15 at 12:54