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

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

    1. Create a New Table

      SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;
      
    2. Drop Column from New Table

      Alter table Table_New drop column id;
      
    3. Add column with identity

      Alter table Table_New add id int primary key identity; 
      
    4. Get All Data in New Table

      SET IDENTITY_INSERT Table_New ON;
      INSERT INTO Table_New (id, Name,CreatedDate,Modified) 
      SELECT id, Name,CreatedDate,Modified FROM Table_Current;
      SET IDENTITY_INSERT Table_New OFF;
      
    5. Drop old Table

      drop table Table_Current;
      
    6. Rename New Table as old One

      EXEC sp_rename 'Table_New', 'Table_Current';
      

提交回复
热议问题