Adding an identity to an existing column

后端 未结 19 2046
温柔的废话
温柔的废话 2020-11-21 13:16

I need to change the primary key of a table to an identity column, and there\'s already a number of rows in table.

I\'ve got a script to clean up the IDs to ensure

19条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 13:45

    you can't do it like that, you need to add another column, drop the original column and rename the new column or or create a new table, copy the data in and drop the old table followed by renaming the new table to the old table

    if you use SSMS and set the identity property to ON in the designer here is what SQL Server does behind the scenes. So if you have a table named [user] this is what happens if you make UserID and identity

    BEGIN TRANSACTION
    SET QUOTED_IDENTIFIER ON
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
    SET ARITHABORT ON
    SET NUMERIC_ROUNDABORT OFF
    SET CONCAT_NULL_YIELDS_NULL ON
    SET ANSI_NULLS ON
    SET ANSI_PADDING ON
    SET ANSI_WARNINGS ON
    COMMIT
    BEGIN TRANSACTION
    
    GO
    
    GO
    CREATE TABLE dbo.Tmp_User
        (
        UserID int NOT NULL IDENTITY (1, 1),
        LastName varchar(50) NOT NULL,
        FirstName varchar(50) NOT NULL,
        MiddleInitial char(1) NULL
    
        )  ON [PRIMARY]
    GO
    
    SET IDENTITY_INSERT dbo.Tmp_User ON
    GO
    IF EXISTS(SELECT * FROM dbo.[User])
     EXEC('INSERT INTO dbo.Tmp_User (UserID, LastName, FirstName, MiddleInitial)
        SELECT UserID, LastName, FirstName, MiddleInitialFROM dbo.[User] TABLOCKX')
    GO
    SET IDENTITY_INSERT dbo.Tmp_User OFF
    GO
    
    GO
    DROP TABLE dbo.[User]
    GO
    EXECUTE sp_rename N'dbo.Tmp_User', N'User', 'OBJECT'
    GO
    ALTER TABLE dbo.[User] ADD CONSTRAINT
        PK_User PRIMARY KEY CLUSTERED 
        (
        UserID
        ) ON [PRIMARY]
    
    GO
    COMMIT
    

    Having said that there is a way to hack the system table to accomplish it by setting the bitwise value but that is not supported and I wouldn't do it

提交回复
热议问题