Aug 17, 2009

Adding Identity column as Primary key to Existing Table

--Create a table as like this:
Create TABLE DataTable(id int, name varchar(20) CONSTRAINT pk_id PRIMARY KEY (id))
--now insert some values for this
Insert into DataTable Values(4, 'test 1')
Insert into DataTable Values(5, 'test 2')
Insert into DataTable Values(6, 'test 3')

--Drop the existing key
ALTER TABLE DataTable DROP CONSTRAINT pk_id

--adding pid as identiry column
ALTER TABLE DataTable add pid int identity(1,1)

--adding the new as primary key
ALTER TABLE DataTable ADD CONSTRAINT pk_DataTable PRIMARY KEY (pid)