Add primary key to a table with many records

make a new table with exact schema and make the desired column the primary key. Now using select to insert copy the records from one table to another. When completed then delete the old table and rename this new table to the desired name.


I know this is older but I ran into this and solved it a different way. Assuming you're using SSMS 2008, you could go into Tools --> Options

Under 'Designers' then 'Table and Database Designers', change the 'Transaction time-out after' value. Default is 30, 0 is for infinite. Try to create the Primary Key after increasing the value.

This tends to be a lot quicker than; creating a new DB, copying the data, deleting the old Db and renaming the new db to the old db. After you're done applying the Primary Key you can set the timeout back to 30 too - if you wish, your choice.

Update Adding a screenshot enter image description here


If in Management Studio you set the primary key in Design view (without saving), when you next right click you have an option "Generate Change Script" - this option is also available on the "Table Designer" menu at the top.

That provides the raw SQL (safely wrapped in a transaction) which you can copy to clipboard, take that over to run as a New Query (button top left, or File > New > Query with Current Connection), paste it in, select the right DB and execute the query.