Answer the question
In order to leave comments, you need to log in
How to deal with nested transaction procedures when calling multiple procedures?
There was a need to write wrappers for old procedures that will call several procedures at once. The old procedures have their own handling of errors and transactions.
No matter how I try to rollback a transaction, there is always an error if something goes wrong
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
CREATE PROCEDURE dbo.Name
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
DECLARE @ErrorCode INT = 0;
DECLARE @ErrorInfo NVARCHAR(2048) = '';
BEGIN TRY
EXEC @ErrorCode = dbo.Name1;
END TRY
BEGIN CATCH
SET @ErrorInfo = ERROR_MESSAGE();
THROW 60000, @ErrorInfo, 1;
END CATCH;
IF @ErrorCode <> 0
BEGIN
SET @ErrorInfo = @ErrorCode;
THROW 60000, @ErrorInfo, 1;
END;
BEGIN TRY
EXEC @ErrorCode = dbo.Name2;
END TRY
BEGIN CATCH
-- Если произошла ошибка то надо откатить транзакцию первой процедуры
SET @ErrorInfo = ERROR_MESSAGE();
THROW 60000, @ErrorInfo, 1;
END CATCH;
IF @ErrorCode <> 0
BEGIN
-- Если произошла ошибка то надо откатить транзакцию первой процедуры
SET @ErrorInfo = @ErrorCode;
THROW 60000, @ErrorInfo, 1;
END;
RETURN 0;
END;
GO
Answer the question
In order to leave comments, you need to log in
Somewhat clumsily, but you can dance from @@TRANCOUNT
Type in catch check @@TRANCOUNT>0 and do rollback , and in normal execution - similar to a commit
But you can catch such enchanting side effects ... so it's better, if possible, to dance from @@TRANCOUNT and start/commit/roll back transactions only at one nesting level
One solution is described in the " Testing SQL Server Code with tSQLt " section "Reversing/Corrupting Transactions"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question