How to change programmatically non-identity column to identity one?

后端 未结 5 1946
终归单人心
终归单人心 2021-01-21 02:27

I have a table with column ID that is identity one. Next I create new non-identity column new_ID and update it with values from ID column + 1. Like this:

new_ID         


        
5条回答
  •  不思量自难忘°
    2021-01-21 03:01

    As far as I know, you have to create a temporary table with the ID field created as IDENTITY, then copy all the data from the original table. Finally, you drop the original table and rename the temporary one. This is an example with a table (named TestTable) that contains only one field, called ID (integer, non IDENTITY):

    BEGIN TRANSACTION
    GO
    CREATE TABLE dbo.Tmp_TestTable
        (
        ID int NOT NULL IDENTITY (1, 1)
        )  ON [PRIMARY]
    GO
    SET IDENTITY_INSERT dbo.Tmp_TestTable ON
    GO
    IF EXISTS(SELECT * FROM dbo.TestTable)
         EXEC('INSERT INTO dbo.Tmp_TestTable (ID)
            SELECT ID FROM dbo.TestTable WITH (HOLDLOCK TABLOCKX)')
    GO
    SET IDENTITY_INSERT dbo.Tmp_TestTable OFF
    GO
    DROP TABLE dbo.TestTable
    GO
    EXECUTE sp_rename N'dbo.Tmp_TestTable', N'TestTable', 'OBJECT' 
    GO
    COMMIT
    

提交回复
热议问题