Adding column with primary key in existing table

非 Y 不嫁゛ 提交于 2020-01-12 02:47:52

问题


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.


回答1:


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



回答2:


You are getting the error because you have existing data that does not fullfill the constraint.

There are 2 ways to fix it:

  • clean up the existing data before adding the constraint
  • add the constraint with the "WITH NOCHECK" option, this will stop sql server checking existing data, only new data will be checked



回答3:


In mysql, I was able to achieve with following query

ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key




回答4:


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




回答5:


k. friend command: sql> alter table tablename add primary key(col_name);

ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);



来源:https://stackoverflow.com/questions/13922360/adding-column-with-primary-key-in-existing-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!