将主键添加到现有 table Sql 服务器时出错

Getting error when adding primary key to existing table Sql server

我有一个 table:Sales_Table 列:

ProductKey Int not null,
UnitPrice decimal 18,2,
SalesAmount decimal 18,2

我正在尝试使用 alter table

将主键添加到 ProductKey 列
ALTER TABLE SALES_TABLE
ADD PRIMARY KEY (ProductKey)

在我 运行 代码之后,我得到以下错误:

Msg 1505, Level 16, State 1, Line 9 The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.Sales_Table' and the index name 'PK__Sales_Ta__A15E99B36F3FE24F'. The duplicate key value is (604).

我该怎么做才能克服这个问题?提前致谢。

试试这个

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Product')
BEGIN
CREATE TABLE [dbo].[Product](
    [ProductKey] [int] NOT NULL,
    [UnitPrice] [decimal](18, 2) NULL,
    [SalesAmount] [decimal](18, 2) NULL,
) ON [PRIMARY]
END

IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE name='Pk_Product')
BEGIN
ALTER TABLE [dbo].[Product] ADD  CONSTRAINT [Pk_Product] PRIMARY KEY CLUSTERED 
(
    [ProductKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END