Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of isolation in nested transactions in SQL Server?

Consider the following SQL:

BEGIN TRAN
SET TRANSACTION ISOLATION LEVEL READ COMMITTED

INSERT Bands
    (  Name  )
SELECT 'Depeche Mode'
UNION
SELECT 'Arcade Fire'

    -- I've indented the inner transaction to make it clearer.

    BEGIN TRAN
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    SELECT *
      FROM Bands

    COMMIT

-- What is the isolation level right here?

UPDATE Bands
   SET Name = 'Modest Mouse'
 WHERE Name = 'Oddest House'

COMMIT

In sum, we start a transaction and set its isolation level to READ COMMITTED. We then do some random SQL and start another, nested transaction. In this transaction we change the isolation level to READ UNCOMMITTED. We then commit that transaction and return to the other.

Now, my guess is that after the inner commit, the isolation level returns to READ COMMITTED. Is this correct?

like image 817
Gregory Higley Avatar asked Oct 21 '08 20:10

Gregory Higley


1 Answers

You [Bob Probst] are correct. Interestingly, according to the documentation you linked:

If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the object returns control the isolation level is reset to the level in effect when the object was invoked. For example, if you set REPEATABLE READ in a batch, and the batch then calls a stored procedure that sets the isolation level to SERIALIZABLE, the isolation level setting reverts to REPEATABLE READ when the stored procedure returns control to the batch.

So, the bottom line here is that SET TRANSACTION ISOLATION LEVEL has procedure affinity, not transaction affinity (as I had thought).

Awesome!

like image 116
Gregory Higley Avatar answered Sep 23 '22 06:09

Gregory Higley