E
E
Evgeny Ezhov2021-02-16 22:44:13
SQL
Evgeny Ezhov, 2021-02-16 22:44:13

What are nested transactions for?

Recently, at interviews, I meet questions related to nested transactions in MS SQL.

BEGIN TRANSACTION
   BEGIN TRANSACTION
      -- Что-то делаем
   COMMIT
ROLLBACK


The question is the same, whether what was confirmed in the internal transaction during the commit will be saved. It is clear logically that it will not.

But I have a question - why, in principle, such nesting is needed, where can it be used?
The only thing that comes to mind is to rollback when an exception occurs (with XACT_ABORT = ON).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2021-02-17
@egecorp

Actually a simple option: an sp with a transaction calls another sp with a transaction, which can be called by itself - that's the "matryoshka" if it doesn't take care of, for example, checking trancount.
Well, architecturally - changes are not yet available outside the nested transaction - sometimes this is exactly what is required.

E
Evgeny Glebov, 2021-02-25
@GLeBaTi

Example:
There are ready-made pieces of code with transactions:
Транзакция 1: Пополнить счёт пользователя
Транзакция 2: Дать скидку пользователю
And there is a transaction that is responsible for registration:
Транзакция 3: Регистрация (создать пользователя)
The task has come: to give the user money and a discount during registration.
You simply add the call of the first two transactions to the third transaction. You get an investment.
You can of course rewrite without nesting, but there is no need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question