I was helping a client change to a new web host. During this process I discovered an Access database was powering part of their web site. This had to go!
I imported the database into SQL Server. Unfortunately, this process removed the identify specifications on the primary key column for one of the tables. This means that the primary key column would not automatically fill in with an automatically incrementing integer. I opened up the table design, and tried to change the field back to an ID. Unfortunately, SQL Server does not allow you to add an identity specification to an existing column on an existing table.
How do I fix that?
What is the Process?
The process was tricky to figure out, but not all that too hard. Basically, do this:
- Create a new table with all the same columns as the old table. Make sure this new table has an identity column.
- Enable Identity Insert on the new table.
- Copy all data from the first table into the new table.
- Disable Identity Insert on the new table.
- Delete the original table.
- Rename the new table to the original table's name.
Then you're done.
What is the Code?
This whole process can be done quickly with a SQL Server script.
First, create the new table:
CREATE TABLE dbo.newtable_temp
Id int NOT NULL IDENTITY(1, 1),
textField nvarchar(100) NULL,
bitField bit not NULL
/* other fields */
Then enable the identity insert:
SET IDENTITY_INSERT dbo. newtable_temp ON
Next, use this script to insert all the rows from the original table into the new table:
IF EXISTS ( SELECT *
FROM dbo.newtable )
INSERT INTO dbo. newtable _temp ( Id, textField, bitField /* other fields */)
SELECT Id, textField, bitField /* other fields */
FROM dbo. newtable TABLOCKX
Then turn off the identity insert:
SET IDENTITY_INSERT dbo.newtable_temp ON
Delete the original table:
DROP TABLE dbo.newtable
Finally rename the old table:
Exec sp_rename 'newtable_temp', 'newtable'
And you should be good to go!
Much thanks to this Stack Overflow question for helping me out.