Eduardo Fuerte
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
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
ASKER
I'm using 2014, could you point the command (or a reference to it) ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER
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! :)
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! :)
I believe that you'll need to run both statements together. Highlight them and run them in a single step.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
ASKER
Really a good solution the 2nd option you give.
Thanks for the guidance!
Thanks for the guidance!
On 2008 and older, no.