I am getting this error in stored procedure.
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.
I read through some of the answers and found that if I return without a commit, I get the error. My stored procedure is something like this:
BEGIN TRY
BEGIN
if @id is null
BEGIN
set @id= (SELECT last_sequence_value FROM table_name WHERE sequence_name = 'id') + 1
BEGIN
BEGIN TRANSACTION
-- update SQL statement here
IF @@ROWCOUNT = 0
BEGIN
ROLLBACK TRANSACTION
RAISERROR('There was an error getting unique id in the table.',10,1)
RETURN
END
IF (@@ERROR <> 0)
BEGIN
ROLLBACK TRANSACTION
RAISERROR('There was an error updating record to the table',10,1)
RETURN
END
COMMIT TRANSACTION
END
END
else
BEGIN
-- some sql select statements
END
END
END TRY
BEGIN CATCH
-- Raise an error with the details of the exception
RAISERROR(@ErrMsg, @ErrSeverity, 1) WITH SETERROR
END CATCH
From the above code, I am doing a rollback and returning from the stored procedure. Yet when I run this in the perf testing environment, I get the error mentioned earlier.
Kindly help regarding this.
ROLLBACK TRANSACTION;since this attempts to undo the caller's transaction. Instead, you must detect whether there is an outer transaction or not, and if there is one, to start a savepoint and rollback to your savepoint instead. It gets messy very quickly. The other option is not to start an inner transaction if there's already an outer transaction, and then just THROW if the proc fails, leaving it to the outer transaction to rollback. - StuartLC