How to use Alter table to set Identity column?

Kindly specify how to use Alter Table to set the Identity Column?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Add MyColumn [int] identity (1, 1) not null

Of course, you cannot change the identity column in this manner once it has been created - this will only allow you to set it on a table that does not already have an identity column.

muktamariwalaAuthor Commented:
but can I associate the Identity to a column which is alreday in the table???
No. You cannot alter an existing column using transact SQL and make it an identity column.

However, you can do what the SQL Enterprise Damager does - create a new temporary table with the structure that you require, set IDENTITY_INSERT ON, insert your data from the old table into the temporary table, drop the old table and rename the new table to have the same name as the old table had.

Of course, this could be a problem if the old table has foreign keys / constraints, triggers, etc - you will have to drop those and apply them to the new table after it has been built.

Ensure that the identity seed is set to the max value of the column - you don't want errors when SQL attempts to create a value that already exists.

Suggest you do all of this in a single transaction - rollback on error.

Also, backup your database first.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: Nightman {http:#9777147}

Please leave any comments here within the next four days.

EE Cleanup Volunteer
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.