22.11.11

How to add an auto increment field to an existing SQL Server table?

I had a requirement at work to add an auto incremented field to an existing SQL Server table. The intention was to generate a new primary key. 
In a few lines, this was made possible.

alter table {TableName} add {IdColumn} int 
declare @Counter int 
set @Counter = 0
UPDATE {TableName} SET @Counter = {IdColumn} = @Counter+1


Thanks to the article @
http://haacked.com/archive/2004/02/28/sql-auto-increment.aspx

0 comments: