Read and Increment int value in SQL Server

前端 未结 2 521
孤独总比滥情好
孤独总比滥情好 2021-01-25 20:39

I need to read and increment a value atomically in SQL Server 2008, using c#.

For example, I have to insert items of a \"lot\", for this i need the number of the last lo

相关标签:
2条回答
  • 2021-01-25 20:41

    The easiest way would be to just alter the table so that the lot number is an identity field and will auto-increment itself. Then you don't have to worry about incrementing in code.

    0 讨论(0)
  • 2021-01-25 21:04

    Is it essential that the lot numbers be sequential? Why not just use an identity? This is better in terms of concurrency as otherwise you need to block concurrent insert attempts in case they get rolled back and would leave a gap in the sequence.

    If it absolutely is a requirement however you can do

    CREATE TABLE dbo.Sequence 
      (
         OneRow CHAR(1) DEFAULT('X') PRIMARY KEY CHECK(OneRow = 'X'),
         val    INT
      )  
    

    Insert a row with an initial seed.

    INSERT INTO dbo.Sequence 
                (val)
    VALUES     (1)  
    

    Then to allocate a range of sufficient size for your insert (call it in the same transaction obviously)

    CREATE PROC dbo.GetSequence
    @val AS int OUTPUT,
    @n as int =1
    AS
    UPDATE dbo.Sequence 
    SET @val = val = (val + @n);
    
    0 讨论(0)
提交回复
热议问题