简体   繁体   中英

Transaction isolation for sql statements

Can we set isolation level for plain SQL statements in a stored procedure in SQL Server 2005/2008?

Case 1: (This will work fine)

CREATE PROCEDURE MySP 
AS 
BEGIN
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    BEGIN TRAN
    SELECT * FROM MyTable
    COMMIT TRAN
END

Case 2: (does this isolation stuff work here?)

CREATE PROCEDURE MySP 
AS 
BEGIN
   SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT * FROM MyTable
END

If case 2 is correct, would it work for several select statements as well?

Yes it will work for multiple select statements.

If you are worried about the lack if a transaction in the second stored procedure you should know that the query is executed under an implicit transaction as opposed to an explicit transaction that you have in the first stored procedure.

Isolation level can be set either at the session level with a session option or at the query level with a table hint. To set isolation level of the whole session we use command:

SET TRANSACTION ISOLATION LEVEL <isolation name>;

You can use a table hint to set the isolation level of a query as:

SELECT ... FROM <table> WITH (<isolationname>);

so in your case it would be like:

SELECT *
FROM MyTable WITH (READCOMMITTEDLOCK);

One thing here to note is: with the session option a space is specified between the words in case the name of the isolation level is made of more than one word, such as REPEATABLE READ . With the query hint,we don't specify a space between the words—for example, WITH (REPEATABLEREAD).

If you use SET TRANSACTION ISOLATION LEVEL in a stored procedure, this transaction isolation level is used for the duration of the stored proc. According to MSDN :

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.

Setting transaction isolation level is not the same as starting a transaction. Transaction isolation level tells SQL Server how to control locking.

If you only have multiple SELECT queries with READ UNCOMMITTED transaction isolation level, putting them all into a transaction won't make practical difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM