SQL Server - Auto-incrementation that allows UPDATE statements

前端 未结 5 2029
礼貌的吻别
礼貌的吻别 2020-11-30 15:22

When adding an item in my database, I need it to auto-determine the value for the field DisplayOrder. Identity (auto-increment) would be an ideal solution, but I need to be

5条回答
  •  星月不相逢
    2020-11-30 15:56

    A solution to this issue from "Inside Microsoft SQL Server 2008: T-SQL Querying"

    CREATE TABLE dbo.Sequence(
     val int IDENTITY (10000, 1) /*Seed this at whatever your current max value is*/
     )
    
    GO
    
    CREATE PROC dbo.GetSequence
    @val AS int OUTPUT
    AS
    BEGIN TRAN
        SAVE TRAN S1
        INSERT INTO dbo.Sequence DEFAULT VALUES
        SET @val=SCOPE_IDENTITY()
        ROLLBACK TRAN S1 /*Rolls back just as far as the save point to prevent the 
                           sequence table filling up. The id allocated won't be reused*/
    COMMIT TRAN
    

    Or another alternative from the same book that allocates ranges easier. (You would need to consider whether to call this from inside or outside your transaction - inside would block other concurrent transactions until the first one commits)

    CREATE TABLE dbo.Sequence2(
     val int 
     )
    
    GO
    
    INSERT INTO dbo.Sequence2 VALUES(10000);
    
    GO
    
    CREATE PROC dbo.GetSequence2
    @val AS int OUTPUT,
    @n as int =1
    AS
    UPDATE dbo.Sequence2 
    SET @val = val = val + @n;
    
    SET @val = @val - @n + 1; 
    

提交回复
热议问题