I am trying to add primary key to newly added column in existing table name Product_Details
.
New Column added: Product_Detail_ID
(int
and not null
)
I am trying add primary key to Product_Detail_ID
(please note: there are no other primary or foreign key assigned to this table)
I am trying with this query but getting error.
ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)
GO
Error:
The
CREATE UNIQUE INDEX
statement terminated because a duplicate key was found for the object name'dbo.Product\_Details'
and the index name'pk\_Product\_Detils'
. The duplicate key value is (0).
Am I missing something here? I am using SQL Server 2008 R2. I would appreciate any help.
Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.
The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.
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
In mysql, I was able to achieve with following query
ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key
You are getting the error because you have existing data that does not fullfill the constraint.
There are 2 ways to fix it:
ALTER TABLE table_name
ADD column_name INT PRIMARY KEY AUTO_INCREMENT FIRST;
Reference: Stack Overflow | Tech On The Net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With