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

后端 未结 5 1322
星月不相逢
星月不相逢 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:35

    I used this SP to handle the case where name does not have a counter initially

    ALTER PROCEDURE [dbo].[GetNext](
    @name   varchar(50) )
    AS BEGIN SET NOCOUNT ON
    
    DECLARE @Out TABLE(Id BIGINT)
    
    MERGE TOP (1) dbo.Counter as Target
        USING (SELECT 1 as C, @name as name) as Source ON Target.name = Source.Name
        WHEN MATCHED THEN UPDATE SET Target.[current] = Target.[current] + 1
        WHEN NOT MATCHED THEN INSERT (name, [current]) VALUES (@name, 1)
    OUTPUT
        INSERTED.[current];
    END
    

提交回复
热议问题