In MS SQL Server, is there a way to “atomically” increment a column being used as a counter?

后端 未结 5 1328
星月不相逢
星月不相逢 2020-12-23 17:21

Assuming a Read Committed Snapshot transaction isolation setting, is the following statement \"atomic\" in the sense that you won\'t ever \"lose\" a concurrent increment?

5条回答
  •  庸人自扰
    2020-12-23 17:31

    There is at heart only one transaction, the outermost one. The inner transactions are more like checkpoints within a transaction. Isolation levels affect only sibling outermost transactions, not parent/child related transactions.

    The counter will be incremented by two. The following yields one row with a value of (Num = 3). (I opened up SMSS and pointed it to a local SQL Server 2008 Express instance. I have a database named Playground for testing stuff.)

    use Playground
    
    drop table C
    create table C (
        Num int not null)
    
    insert into C (Num) values (1)
    
    begin tran X
        update C set Num = Num + 1
        begin tran Y
            update C set Num = Num + 1
        commit tran Y
    commit tran X
    
    select * from C
    

提交回复
热议问题