SQL Server transaction and SELECT statement

前端 未结 2 1012

I often saw many people use SELECT statement within a transaction. I often use insert/update/delete only in transaction. I just do not understand t

2条回答
  •  别那么骄傲
    2020-12-29 07:38

    One of the main reasons I can think of (the only reason, in fact) is if you want to set a different isolation level, eg:

    USE AdventureWorks2008R2;
    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
    BEGIN TRANSACTION;
    
    SELECT * FROM HumanResources.EmployeePayHistory;
    
    SELECT * FROM HumanResources.Department;
    
    COMMIT TRANSACTION;
    

    For single SELECT statements though, I'm not so sure, unless you had a reason to go the other way and set READ UNCOMMITTED in cases where response time/maximising concurrency is more important than accurate or valid data.

    If the single SELECT statement is inside an explicit transaction without altering the isolation levels, I'm pretty sure that will have no effect at all. Individual statements are, by themselves, transactions that are auto-committed or rolled back on error.

提交回复
热议问题