SQL Server Adding column with primary key in existing table

6ju8rftf  于 2023-04-10  发布在  其他
关注(0)|答案(8)|浏览(232)

I am trying to add primary key as newly added column Product_Detail_ID ( int and not null ) in existing table name Product_Details . But I am gettin an error.

(There are no other primary or foreign keys assigned to this table.)

ALTER TABLE Product_Details
ADD CONSTRAINT pk_Product_Detils_Product_Detail_ID PRIMARY KEY(Product_Detail_ID)

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).

What am I missing?

I am using SQL Server 2008 R2.

rseugnpd

rseugnpd1#

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
alen0pnh

alen0pnh2#

In mysql, I was able to achieve with following query

ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key

vxf3dgd4

vxf3dgd43#

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
ma8fv8wu

ma8fv8wu4#

Add Primary Key to First Position
ALTER TABLE table_name 
ADD column_name INT PRIMARY KEY AUTO_INCREMENT FIRST;

Reference: Stack Overflow | Tech On The Net

qaxu7uf2

qaxu7uf25#

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

jv4diomz

jv4diomz6#

If you want to add a new column say deptId to the existing table say department then you can do it using the below code.

ALTER TABLE department ADD COLUMN deptID INT;

it will create your new column named deptID.

now if you want to add constraint also along with new column while creating it then you can do it using the below code. In the below code I am adding primary key as a constraint. you can add another constraint also instead of primary key like foreign key, default etc.

ALTER TABLE department ADD COLUMN deptID INT NOT NULL ADD CONSTRAINT PRIMARY KEY(deptID);
wsewodh2

wsewodh27#

For SQL Server:

ALTER TABLE table_name ADD column_name INT identity(1,1) NOT NULL PRIMARY KEY;

huus2vyu

huus2vyu8#

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

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

相关问题