sql - Adding an identity to an existing column -


I need to change the primary key of a table into an identity column, and there are already several rows in the table < / P>

I have got a script to clear the ID to ensure that they are starting sequentially on 1, works fine on my test database

What is the SQL command to retain the identity property of the column?

You have 2 options,

    < Li>

    Create a new table with identification; Current table drop

  1. create a new column with the ID; Existing column drop

approach 1. ( new table ) Here you can maintain existing data values ​​on newly created identity columns.

go to identity_insert dbo.Tmp_Names

prefix ID (id not integer not recognize NULL (1, 1), name varchar (50) zero) [primary] if exists ( Select * dbo.names from dbo.Tmp_Names (numbers, names), select the name dbo.Names go from TABLOCKX to go to identity_insert dbo.Tmp_Names go off the drop table dbo.Names Exec sp_rename go to 'Tmp_Names',' Name '

approach2 ( new column ) You can not have existing data values ​​on the newly created identity column, the Identity column number Region sequence will catch on.

  Alter table name Id_new int identity added (1, 1) Get Alter table name drop column ID Go Exec sp_rename 'Names.Id_new', 'id', 'column'  < / Pre> 

For more details see the following Microsoft SQL Server Forums Post:


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -