Using a trigger to simulate a second identity column in SQL Server 2005

后端 未结 5 1769
我寻月下人不归
我寻月下人不归 2020-12-20 07:46

I have various reasons for needing to implement, in addition to the identity column PK, a second, concurrency safe, auto-incrementing column in a SQL Server 2005 database.

5条回答
  •  悲&欢浪女
    2020-12-20 08:23

    A solution to this issue from "Inside Microsoft SQL Server 2008: T-SQL Querying" is to create another table with a single row that holds the current max value.

    CREATE TABLE dbo.Sequence(
     val int 
     )
    

    Then to allocate a range of sufficient size for your insert

    CREATE PROC dbo.GetSequence
    @val AS int OUTPUT,
    @n as int =1
    AS
    UPDATE dbo.Sequence 
    SET @val = val = val + @n;
    
    SET @val = @val - @n + 1; 
    

    This will block other concurrent attempts to increment the sequence until the first transaction commits.

    For a non blocking solution that doesn't handle multi row inserts see my answer here.

提交回复
热议问题