How do I add the identity property to an existing column in SQL Server

后端 未结 6 1255
夕颜
夕颜 2020-12-09 02:22

In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?

Something like:

alter table tblFoo 
            


        
6条回答
  •  没有蜡笔的小新
    2020-12-09 02:33

    The solution posted by Vikash doesn't work; it produces an "Incorrect syntax" error in SQL Management Studio (2005, as the OP specified). The fact that the "Compact Edition" of SQL Server supports this kind of operation is just a shortcut, because the real process is more like what Robert & JohnFX said--creating a duplicate table, populating the data, renaming the original & new tables appropriately.

    If you want to keep the values that already exist in the field that needs to be an identity, you could do something like this:

    CREATE TABLE tname2 (etc.)
    INSERT INTO tname2 FROM tname1
    
    DROP TABLE tname1
    CREATE TABLE tname1 (with IDENTITY specified)
    
    SET IDENTITY_INSERT tname1 ON
    INSERT INTO tname1 FROM tname2
    SET IDENTITY_INSERT tname1 OFF
    
    DROP tname2
    

    Of course, dropping and re-creating a table (tname1) that is used by live code is NOT recommended! :)

提交回复
热议问题