tags:

views:

53

answers:

4

Hello,

I have a table without a PK. The table has about 500 rows so I don't want to write them manually. What's the best way to add a PK?

Thank you,

Rafa

+2  A: 
ALTER TABLE T ADD PkColumn INT NOT NULL IDENTITY
ALTER TABLE T ADD CONSTRAINT PK_T PRIMARY KEY (PkColumn)
JohnOpincar
A: 

Hm.. simple program which reads all records and inserts them to new table with PK?

Roman
A: 
ALTER TABLE CurrentTable ADD pkNewColumn INT IDENTITY (1,1) NOT NULL
ALTER TABLE CurrentTable ADD CONSTRAINT PK_pkNewColumn PRIMARY KEY (pkNewColumn)
Rich.Carpenter
Why truncate the table and reinsert the rows?
JohnOpincar
Good point. No real need. Edited to reflect this.
Rich.Carpenter
A: 

Depends on if your adding a new column that will be a primary key or if you want to designate an existing column as a primary key. To modify an existing column:

Create a clone of your current table, and backup the 500 rows using a

INSERT INTO BACKUP_TABLE ( COLA, COLB, COLC ) SELECT COLA, COLB,COLC FROM TABLE;

Then recreate your original table with the primary key, and copy the backup table into the original using a similary SQL statement as above.

i_like_caffeine