Skip to content
Advertisement

Cannot rollback while a subtransaction is active – Error 2D000

I have written a stored procedure that basically loops over an array of fields and performs some manipulation in the db for each iteration. What I want to achieve is, either all the iterations of loops should occur or neither one of them should occur.

So let’s say there were 5 elements in the fields array and the loop iterates up to the 3rd element before noticing that some condition is true and throwing an error, I want to rollback all the changes that occurred during the first 2 iterations. I’ve used ROLLBACK statements to achieve the same, but every time it reaches the ROLLBACK statement it throws the following error:

Cannot rollback while a subtransaction is active : 2D000

Surprisingly, it works as normal if I comment out the outobj := json_build_object('code',0); statement within the EXCEPTION WHEN OTHERS THEN block or if I remove that whole block completely.

I’ve checked the PostgreSQL documentation for error codes, but it didn’t really help. My stored procedure is as follows:

Advertisement

Answer

Explanation:

Based on the clue provided by @Laurez Albe, I came up with a cleaner way to solve the above problem.

Basically, what I’ve done is, I’ve raised a custom exception whenever a condition is true. So when an exception is thrown, all the changes made by block X are rolled back gracefully. I can even perform last minute cleanup within the exception conditional blocks.

Implementation:
Demo:

Dbfiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement