Search code examples
sqlsql-serverprimary-keycomposite-primary-key

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


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?


Solution

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