Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Nested transactions in internal SP - RollBack

$
0
0

Hi,

I have internal SP as follows:   

CREATE PROCEDURE [dbo].[Internal_SP]  
 @lngID int 
AS  
begin
set nocount OFF;
insert into dbo.Table_Test_1 (id, txt)
select @lngID, 'Internal SP 1';
end;

The main SP which is calling Internal SP as follows:

CREATE PROCEDURE [dbo].[Outer_SP]  
 @lngID int 
AS  
begin

begin try
begin tran
exec [dbo].[Inernal_SP] @lngID;    -- Internal SP calling here.

insert into dbo.Table_Test_2 (id, text) select @lngID, 'Outer SP 1';

COMMIT Tran
END TRY  
----- If any error rollback the complete transaction and log the error.  
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000),@ErrorSeverity INT,@ErrorState INT
SELECT  @ErrorMessage=ERROR_MESSAGE(),@ErrorSeverity=ERROR_SEVERITY(), @ErrorState=ERROR_STATE()
    IF @@TRANCOUNT > 0    ROLLBACK TRAN 
    PRINT 'Transaction AFTER Rolled back--' + cast(@@TRANCOUNT as varchar(100))
PRINT 'Error message: ' + @ErrorMessage   

RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState)
END CATCH
END

The scenarios: 

1. Happy Path : If everything works well, all two tables will be inserted with a single record.

2. Error in Internal SP: The table Table_Test_1 should be rolled back, as it won't execute of Table_Test_2 table.

3. Error in Outer SP: The tables Table_Test_1 and Table_Test_2 should be rolled back.

How to ROLL BACK the transaction when it's nested SP to SP calling transactions? Kindly help me out.

Many Thanks,

Satish Marreddy



Viewing all articles
Browse latest Browse all 23857

Trending Articles