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

后端 未结 5 1773
我寻月下人不归
我寻月下人不归 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:19

    Just an idea, if you have 2 "identity" columns, then surely they would be 'in sync' - if not exactly the same value, then would differ by a constant value. If so, then why not add the "second identity" column as a COMPUTED column, which offsets the primary identity? Or is my logic flawed here?

    Edit : As per Martin's comment, note that your calc might need to be N * id + C, where N is the Increment and C the offset / delta - excuse my rusty maths.

    For example:

    ALTER TABLE MyTable ADD OtherIdentity AS Id * 2 + 1;
    

    Edit Note that for Sql 2012 and later, that you can now use an independent sequence to create two or more independently incrementing columns in the same table.

    Note: OP has edited the original requirement to include reclaiming sequences (noting that identity columns in SQL do not reclaim used ID's once deleted).

提交回复
热议问题