Sql-server – How to force a minimum isolation level in a procedure

lockingsql servertransaction

How can I force a minimum isolation level in a procedure in mssql?

I can use "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;" inside my procedure to set the transaction-level. But this command will downgrade the isolation level if the caller/executor uses e.g. "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;" How can I force a minimum isolation level without downgrading a higher isolation level?

What happens if I commit the "nested" transaction in my procdure? Will the locks acquired by the nested transaction remain until the outer transaction (of the caller) is committed?

Best Answer

There are a couple of options for determining the transaction isolation level in SQL Server depending on whether you want to include read committed snapshot as separate from read committed. Once you know what isolation level your session is using, you can implement whatever logic you want. Something like

IF EXISTS( SELECT 1
             FROM sys.dm_exec_sessions 
            WHERE session_id = @@SPID
              AND transaction_isolation_level < 3 )
BEGIN
  set transaction isolation level repeatable read;
END;