I am trying to add primary key to newly added column in existing table name Product_Details
.
New Column added: Product_Detail_ID
(int
If you want SQL Server to automatically provide values for the new column, make it an identity.
ALTER TABLE Product_Details DROP COLUMN Product_Detail_ID
GO
ALTER TABLE Product_Details ADD Product_Detail_ID int identity(1,1) not null
GO
ALTER TABLE Product_Details
add CONSTRAINT pk_Product_Detils_Product_Detail_ID primary key(Product_Detail_ID)
GO
ALTER TABLE Jaya
ADD CONSTRAINT no primary key(No);
here Jaya
is table name,
no
is column name,
ADD CONSTRAINT
is we giving the primary key keyword
k. friend command: sql> alter table tablename add primary key(col_name);
ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);
You are getting the error because you have existing data that does not fullfill the constraint.
There are 2 ways to fix it:
In mysql, I was able to achieve with following query
ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key