Link to home
Start Free TrialLog in
Avatar of Eduardo Fuerte
Eduardo FuerteFlag for Brazil

asked on

Is it possible to make a SQLServer table's PK column to be indentity after the table is populated?

Hi Experts!

Is it possible to transform an existing PK column to be an indentity column too, after the table is populated?

How could I do that?

Thanks in advance
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

That would depend on the version of SQL Server that you're running.

On 2008 and older, no.
Avatar of Eduardo Fuerte

ASKER

I'm using 2014, could you point the command (or a reference to it) ?
ASKER CERTIFIED SOLUTION
Avatar of Russ Suter
Russ Suter

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As far as I know, there is no magic one-line command.  But you can still do it.  If there are no foreign keys that reference that column, the easiest is to

ALTER TABLE {mytable} ADD {newcolumn} INT IDENTITY(1,1) NOT NULL;

Copy the values in the PK to the new column.
Drop the old PK column.
Rename the new column to the same name as the dropped column.

If there are foreign keys against the table, it gets a lot more involved.
Hi

Going the easyest way

User generated image
It's not possible to update the identity column with the old values...
Set IDENTITY_INSERT ON

and you should be able to update the row to have the values in the original row.

Remember to set IDENTITY_INSERT OFF again when you're done!  :)
Even doing that

User generated image
I believe that you'll need to run both statements together.  Highlight them and run them in a single step.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Since I'm doing a migration data that must preserve the table codes, I have to go this way... just a little more time...
Also remember that this will affect any foreign keys that are in place.  You'll have to reestablish them.
Really a good solution the 2nd option you give.

Thanks for the guidance!