Possible to implement a manual increment with just simple SQL INSERT?

后端 未结 11 1836
刺人心
刺人心 2021-01-05 11:54

I have a primary key that I don\'t want to auto increment (for various reasons) and so I\'m looking for a way to simply increment that field when I INSERT. By simply, I mean

11条回答
  •  情话喂你
    2021-01-05 12:21

    You understand that you will have collisions right?

    you need to do something like this and this might cause deadlocks so be very sure what you are trying to accomplish here

    DECLARE @id int
    BEGIN TRAN
    
        SELECT @id = MAX(id) + 1 FROM Table1 WITH (UPDLOCK, HOLDLOCK)
        INSERT INTO Table1(id, data_field)
        VALUES (@id ,'[blob of data]')
    COMMIT TRAN
    

    To explain the collision thing, I have provided some code

    first create this table and insert one row

    CREATE TABLE Table1(id int primary key not null, data_field char(100))
    GO
    Insert Table1 values(1,'[blob of data]')
    Go
    

    Now open up two query windows and run this at the same time

    declare @i int
    set @i =1
    while @i < 10000
    begin
    BEGIN TRAN
    
    INSERT INTO Table1(id, data_field)
    SELECT MAX(id) + 1, '[blob of data]' FROM Table1
    
    COMMIT TRAN;
    set @i =@i + 1
    end
    

    You will see a bunch of these

    Server: Msg 2627, Level 14, State 1, Line 7 Violation of PRIMARY KEY constraint 'PK__Table1__3213E83F2962141D'. Cannot insert duplicate key in object 'dbo.Table1'. The statement has been terminated.

提交回复
热议问题