Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I alter a primary key constraint using SQL syntax?

Tags:

sql-server

I have a table that is missing a column in its primary key constraint. Instead of editing it through SQL Server, I want to put this in a script to add it as part of our update scripts.

What syntax can I use to do this? Must I drop and recreate the key constraint?

like image 278
Jason Rae Avatar asked Jan 06 '12 17:01

Jason Rae


People also ask

Can you alter a primary key?

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.


2 Answers

Yes. The only way would be to drop the constraint with an Alter table then recreate it.

ALTER TABLE <Table_Name> DROP CONSTRAINT <constraint_name>  ALTER TABLE <Table_Name> ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>) 
like image 164
darnir Avatar answered Oct 06 '22 10:10

darnir


PRIMARY KEY CONSTRAINT cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.

like image 25
Oleg Dok Avatar answered Oct 06 '22 11:10

Oleg Dok