Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new identity column to a table in SQL Server?

Tags:

I am using SQL Server 2008 Enterprise. I want to add an identity column (as unique clustered index and primary key) to an existing table. Integer based auto-increasing by 1 identity column is ok. Any solutions?

BTW: my most confusion is for existing rows, how to automatically fill-in new identity column data?

thanks in advance, George

like image 734
George2 Avatar asked Sep 13 '10 08:09

George2


People also ask

How can I add an identity column to an existing table in SQL Server?

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.

How can create identity column in SQL Server query?

Syntax for SQL Server Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) . VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table. The "Personid" column would be assigned a unique value.

Can identity column be updated?

You can not update identity column. SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement.


1 Answers

you can use -

alter table <mytable> add ident INT IDENTITY 

This adds ident column to your table and adds data starting from 1 and incrementing by 1.

To add clustered index -

CREATE CLUSTERED INDEX <indexName> on <mytable>(ident)  
like image 137
Sachin Shanbhag Avatar answered Sep 21 '22 12:09

Sachin Shanbhag