Is T-SQL Stored Procedure Execution 'atomic'?

后端 未结 5 1887
甜味超标
甜味超标 2021-01-04 01:16

Let\'s say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):

CREATE PROCEDURE incrementCounte         


        
5条回答
  •  耶瑟儿~
    2021-01-04 01:49

    Maybe I'm reading too much into your example (and your real situation may be significantly more complicated), but why wouldn't you just do this in a single statement?

    CREATE PROCEDURE incrementCounter AS
    
    UPDATE
        MyTable
    SET
        CounterColumn = CounterColumn + 1
    
    GO
    

    That way, it's automatically atomic and if two updates are executued at the same time, they'll always be ordered by SQL Server so as to avoid the conflict you describe. If, however, your real situation is much more complicated, then wrapping it in a transaction is the best way to do this.

    However, if another process has enabled a "less safe" isolation level (like one that allows dirty reads or non-repeatable reads), then I don't think a transaction will protect against this, as another process can see into the partially updated data if it's elected to allow unsafe reads.

提交回复
热议问题