Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolation Level for stored procedure SQL Server?

I want to add Isolation level in my procedure and for that I wanted to confirm that which one is the correct format from below:

Attempt #1 - setting isolation level before calling the stored procedure:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

EXEC [sp_GetProductDetails] 'ABCD','2017-02-20T11:51:37.3178768'

Attempt #2 - setting isolation level inside the stored procedure:

CREATE PROCEDURE MySP AS
BEGIN
   SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
   BEGIN TRAN 
       SELECT * FROM MyTable
       SELECT * FROM MyTable2
       SELECT * FROM MyTable3

       COMMIT TRAN  
END

Please suggest.

like image 447
Boss Avatar asked Feb 21 '17 06:02

Boss


People also ask

Which isolation level is best in SQL Server?

Serializable. This is the highest isolation level and prevents all possible types of concurrency phenomena in SQL Server, but on the other hand, the serializable level decreases performance and increases the likelihood of deadlocks.

What is the difference between CS and RR isolation levels?

Under an RR isolation level all page locks are held until they are released by a COMMIT (or ROLLBACK), whereas with CS read-only page locks are released as soon as another page is accessed. Repeatable read is the default isolation level if none is specified at BIND time.


1 Answers

Both versions are "correct" - they just do different things:

  • Your attempt #1 sets the isolation level for that database and connection - that means, the chosen isolation level will be used for any future statement - until you change the isolation level again

  • Your attempt #2 sets the isolation level only INSIDE the stored procedure - so once the stored procedure is completed, the isolation level that existed on the database/connection level is restored again

So it really depends on what you want to do:

  • set the isolation level to a different level in general for your current connection to this database? Any future statement will be run under this isolation level --> choose #1

  • set the isolation level to a different setting for just a single stored procedure - regardless of what the connnection/database had before - then use #2

like image 119
marc_s Avatar answered Oct 16 '22 12:10

marc_s