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

后端 未结 5 1945
终归单人心
终归单人心 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 02:35

    Looks like SQL Mobile supports altering a columns identity but on SQL Server 2005 didn't like the example from BOL.

    So your options are to create a new temporary table with the identity column, then turn Identity Insert on:

    Create Table Tmp_MyTable ( Id int identity....)
    
    SET IDENTITY_INSERT dbo.Tmp_Category ON
    
    INSERT Into Tmp_MyTable (...)
    Select From MyTable ....
    
    Drop Table myTable
    
    EXECUTE sp_rename N'dbo.Tmp_MyTable', N'MyTable', 'OBJECT' 
    

    Additionally you can try and add the column as an identity column in the first place and then turn identity insert on. Then drop the original column. But I am not sure if this will work.

    0 讨论(0)
  • 2021-01-21 02:50

    From SqlServerCentral.com

    Changing from Non-IDENTITY to IDENTITY and vice versa

    0 讨论(0)
  • 2021-01-21 02:55

    Guessing you didn't have much luck with your task....

    In table design, you should be able to go into properties and under Identity Specification change (Is Identity) to Yes and assign the column primary key if it formerly had the primary key.

    0 讨论(0)
  • 2021-01-21 02:56

    An Identity is a property that is set at the time the table is created or a new column is added in alter table statement. You can't alter the column and set it to identity and it is impossible to have two identity columns within the same table.

    Depending on the size of the table, is it possible to simply create a new table? copy over the schema of the old one and then use SET IDENTITY_INSERT ON to populate the new identity column with what you want from the old one.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题