views:

55

answers:

4

In all my searching I see that you essentially have to copy the existing table to a new table to chance to identity column for pre-2008, does this apply to 2008 also?

thanks.

most concise solution I have found so far:

CREATE TABLE Test 
 ( 
   id int identity(1,1), 
   somecolumn varchar(10) 
 ); 

 INSERT INTO Test VALUES ('Hello'); 
 INSERT INTO Test VALUES ('World'); 


 -- copy the table. use same schema, but no identity 
 CREATE TABLE Test2 
 ( 
   id int NOT NULL, 
   somecolumn varchar(10) 
 ); 

 ALTER TABLE Test SWITCH TO Test2; 

 -- drop the original (now empty) table 
 DROP TABLE Test; 

 -- rename new table to old table's name 
 EXEC sp_rename 'Test2','Test'; 

 -- see same records 
 SELECT * FROM Test; 
A: 

In all of the new feature documents I read about 2008, adding identity to an existing column was not a feature I recall. The solution you've found is correct and I think the process of adding identity increment to a column automatically would be only rarely useful.

marr75
we have the same table on a "server" DB and a client DB, one does not have the identity, I need to create test data in the one w/o the identity.
You don't need an IDENTITY column to dump test data into a table. Can't you just use ROW_NUMBER() and explicitly populate that column? If you are creating test data, can't you just drop the table and re-create it right in the first place?
Aaron Bertrand
This is how the table is suppossed to be, not identity field in the local DB.Can you give an example insert with Row_Number()?thanks.
I think this will work:INSERT INTO Test(id,somecolumn)SELECT ROW_NUMBER() OVER (ORDER BY id), somecolumnFROM Test2
A: 

Well you can do something like this.

ALTER TABLE my_table ADD ID_COLUMN INT IDENTITY (1,1) NOT NULL
no_one
I don't think this works from all I have read, and the responses above.
This adds a new column, it does not add the IDENTITY property to an existing column.
Aaron Bertrand
Yes, but then probably it might be easier to add a separate identity column and then drop the existing one - unless he is already using it as a primary key with FK relations to other tables.
no_one
A: 

You can add the IDENTITY property to an existing column using the GUI of Enterprise Manager / Management Studio.

Developer Art
If it works like SQL 2005 and earlier, what SSMS is really doing is creating a new table, copying the data over, dropping the old table, and renaming the new one to the new name. Have SSMS script it out and check what's really going on. (Maybe it IS updating an existing colum?!)
Philip Kelley
Thank, yes I know.
Just a warning, don't have SSMS do this on a large table, unless your database is in some kind of maintenance mode and users accessing this table aren't actively connecting.
Aaron Bertrand
A: 

In SQL 2005 and earlier, you could not modify an existing column to become an identity column. I deem it very very unlikely that MS changed that in 2008.

Philip Kelley