How to insert an auto_increment key into SQL Server table

后端 未结 4 1081
孤独总比滥情好
孤独总比滥情好 2020-12-15 10:54

I want to insert rows into a table that has a unique, non auto-incremented primary key.

Is there a native SQL function to evaluate the last key and increment it or d

4条回答
  •  孤街浪徒
    2020-12-15 11:20

    In my opinion the best answer is to fix your table so that the PK column is an identity column. (Please see my comments on the answer from Sebastian Meine about why your currently selected answer is not best.) The only way to make an existing PK become an identity column is by swapping out the table. Roughly:

    BEGIN TRAN;
    -- Rename all constraints in original table
    EXEC sp_rename 'dbo.YourOriginalTable.PK_ConstraintName', 'PKConstraint_Backup';
    EXEC sp_rename 'dbo.YourOriginalTable.OtherConstraintName', 'OtherConstraintName_Backup';
    CREATE TABLE dbo.WorkTable (
        YourPKColumn int identity(1, 1) NOT NULL -- your PK converted to identity
        CONSTRAINT PK_YourOriginalTableConstraintName PRIMARY KEY CLUSTERED,
        AllOtherColumns -- all your other columns exactly as in the original table
    );
    
    SET IDENTITY_INSERT dbo.WorkTable ON;
    INSERT dbo.WorkTable (YourPKColumn, AllOtherColumns)
    SELECT YourPKColumn, AllOtherColumns
    FROM dbo.YourOriginalTable WITH (TABLOCKX, HOLDLOCK);
    
    SET IDENTITY_INSERT dbo.WorkTable OFF;
    
    -- Drop all FK constraints from other tables pointing to your table
    ALTER TABLE dbo.TableWithFK_1
    DROP CONSTRAINT FK_TableWithFK_1_YourOriginalTableSomethingID;
    
    -- Swap out the tables
    EXEC sp_rename 'dbo.YourOriginalTable', 'YourOriginalTableBackup';
    EXEC sp_rename 'dbo.WorkTable', 'YourOriginalTable';
    
    -- If you didn't add them in the WorkTable creation,
    -- add all other removed or needed constraints creation
    ALTER TABLE dbo.YourOriginalTable
    ADD CONSTRAINT OriginalConstraint (OriginalConstraintColumns);
    -- Add back FK constraints from other tables to this one.
    COMMIT TRAN;
    

    You now have a table that has an identity column with a clustered PK on it. You can insert to it no problem. No more concurrency issues and silly SELECT Max() + 1 junk that is so easy to get wrong.

提交回复
热议问题