16

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Boss
  • 195
  • 1
  • 1
  • 7

2 Answers2

22

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

ISOLATION LEVEL READ COMMITTED is default ISOLATION for SQL database.

Attempt #2 is good practice to set ISOLATION LEVEL.

user2771704
  • 5,994
  • 6
  • 37
  • 38