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

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

    This is probably a terrible idea, but it works in at least a limited use scenario

    Just use a regular identity and reseed on deletes.

    create table reseedtest (
       a int identity(1,1) not null,
       name varchar(100)
    )
    
    insert reseedtest values('erik'),('john'),('selina')
    select * from reseedtest
    
    go
    CREATE TRIGGER TR_reseedtest_D ON reseedtest FOR DELETE
    AS
    BEGIN TRAN
    DECLARE @a int
    SET @a = (SELECT TOP 1 a FROM reseedtest WITH (TABLOCKX, HOLDLOCK))
    --anyone know another way to lock a table besides doing something to it?
    DBCC CHECKIDENT(reseedtest, reseed, 0)
    DBCC CHECKIDENT(reseedtest, reseed)
    COMMIT TRAN
    GO
    
    delete reseedtest where a >= 2
    insert reseedtest values('katarina'),('david')
    select * from reseedtest
    
    drop table reseedtest
    

    This won't work if you are deleting from the "middle of the stack" as it were, but it works fine for deletes from the incrementing end.

    Reseeding once to 0 then again is just a trick to avoid having to calculate the correct reseed value.

提交回复
热议问题