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

后端 未结 5 1947
终归单人心
终归单人心 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.

提交回复
热议问题