SQL Server: how to set default isolation level for

2019-04-20 17:12发布

问题:

If right after BEGIN I have SET TRANSACTION ISOLATION LEVEL ... statement, will the given transaction level in force for the entire scope of the stored procedure regardless if I use BEGIN TRANSACTION or not? Namely if I have simple SELECT statements, which are atomic/transacted by definition, will the default transaction level for them set to the given one?

BEGIN
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
 -- will a transaction level for a atomic transaction created by SQL Server for this statement be READ COMMITTED 
SELECT * FROM T
END

回答1:

First, the default isolation level in SQL Server is Read Committed, so that statement doesn't really do anything unless you've changed the default isolation level.

But, in general, yes, SET Transaction Isolation Level will change the isolation level for the whole procedure (the duration of the connection, in fact)

Keep in mind that all SQL statements are implicit transactions meaning that if, for example, an update fails 99% through, it will rollback automatically; no BEGIN TRAN/COMMIT is necessary.

To answer your question, yes, your SELECT statements will inherit the isolation level you set (or the default if you do not set one) unless you override the behavior with a query hint like WITH NOLOCK which will make the individual query behave as though you did SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED