SQL Server - Auto-incrementation that allows UPDATE statements

前端 未结 5 2031
礼貌的吻别
礼貌的吻别 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 16:19

    You way works fine (with a little modification) and is simple. I would wrap it in a transaction like @David Knell said. This would result in code like:

    CREATE PROCEDURE [dbo].[AddItem]
    
    AS
    
    DECLARE @DisplayOrder INT
    
    BEGIN TRANSACTION
    
    SET @DisplayOrder = (SELECT MAX(DisplayOrder) FROM [dbo].[MyTable]) + 1
    
    INSERT INTO [dbo].[MyTable] ( DisplayOrder ) VALUES ( @DisplayOrder )
    
    COMMIT TRANSACTION
    

    Wrapping your SELECT & INSERT in a transaction guarantees that your DisplayOrder values won't be duplicated by AddItem. If you are doing a lot of simultaneous adding (many per second), there may be contention on MyTable but for occasional inserts it won't be a problem.

提交回复
热议问题