I have a linked Server connected from ServerA to ServerB. In each server there is an SP that initiates a transaction and it is necessary for one ServerA.SP to be executed within ServerB.SP. My problem is that when doing that, I get the error:
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements.
I have searched for information about that error but the questions/answers do not include linkedServers. That's why I'm here. The code is something like that, its really simple:
CREATE OR ALTER PROCEDURE #DB1_sp
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION
EXEC [LinkedServer].[db].[Schema].[SP]
... params ...
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
EXEC [Logs].[SetError]
END CATCH
END
GO
EXEC #DB1_sp
On the LinkedServer side, the SP is almost the same code. In fact all my code works if we remove the BEGIN TRANSACTION
, but that is not an option due to the initial validations.
I have tried looking into DISTRIBUTED TRANSACTIONS
, SAVE TRANSACTIONS
and statements like SET XACT_ABORT ON
all of that in the top stored procedure (because I can't access/edit the inner SP) but it doesn't work.