views:

94

answers:

3

Is there an easy way to add an ID (Identity(1,1) & PK) column to a table that already has data?

I have picked up a project that was freelanced out to a horrible developer that didn't put a PK, index or anything on the tables he made.

Now that I am LINQ-ifying it, I have no PK to insert or update off of.

+4  A: 
ALTER TABLE MyTable ADD id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED
AlexCuse
A: 

Open up SQL Server Management Studio
Right click the table
Click Modify
Add the Column
Set the Properties ((Is Identity) Yes, Identity Seed 1, Identity Increment 1)
Right click the Column
Click Set Primary Key
Ctrl-S

Jason Punyon
+1  A: 

I'd be tempted to do it in three stages -

  1. Create a new table with all the same columns, plus you primary key column (script out the table and then alter it to add a PK field)
  2. Insert into the new table all of the values from the old table
  3. Once your happy with it, delete the old table and rename your new one with the Primary Key the same as the old table.
Russ Cam