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

后端 未结 6 1251
夕颜
夕颜 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:45

    There is no direct way of doing this except:

    A) through SQL i.e.:

    -- make sure you have the correct CREATE TABLE script ready with IDENTITY
    
    SELECT * INTO abcTable_copy FROM abcTable
    
    DROP TABLE abcTable
    
    CREATE TABLE abcTable -- this time with the IDENTITY column
    
    SET IDENTITY_INSERT abcTable ON
    
    INSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy
    
    SET INDENTITY_INSERT abcTable OFF
    
    DROP TABLE abcTable_copy 
    
    -- I would suggest to verify the contents of both tables 
    -- before dropping the copy table
    

    B) Through MSSMS which will do exactly the same in the background but will less fat-fingering.

    • In the MSSMS Object Explorer right click the table you need to modify
    • Select "design" Select the column you'd like to add IDENTITY to
    • Change the identity setting from NO -> YES (possibly seed)
    • Ctr+S the table

    This will drop and recreate the table with all original data in it. If you get a warning:

    Go to MSSMS Tools -> Options -> Designers -> Table and database Designers and uncheck the option "Prevent saving changes that require table re-creation"

    Things to be careful about:

    1. your DB has enough disk space before you do this
    2. the DB is not in use (especially the table you are changing)
    3. make sure to backup your DB before doing it
    4. if the table has a lot of data (over 1G) try it somewhere else first before using in real DB

提交回复
热议问题