我正在尝试将主键添加到现有表名称 Product_Details
中新添加的列。
添加了新列:Product_Detail_ID
(int
和 not null
)
我正在尝试将主键添加到 Product_Detail_ID
(请注意:没有其他主键或外键分配给此表)
我正在尝试使用此查询但出现错误。
ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)
GO
错误:
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).
我是不是漏掉了什么?我正在使用 SQL Server 2008 R2。如果有任何帮助,我将不胜感激。
最佳答案
如果您希望 SQL Server 自动为新列提供值,请将其设为标识。
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
关于sql - 在现有表中添加具有主键的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13922360/