问题
I have this code:
ALTER TABLE FishSticks
ADD MyNewIdentityColumnId INT IDENTITY(1,1) NOT NULL
SET IDENTITY_INSERT FishSticks ON
UPDATE FishSticks
SET MyNewIdentityColumnId = MyOldColumnId
However it says:
Cannot update identity column 'MyNewIdentityColumnId'.
I assume this is due to SQL Azure, but I didn't have much success googling. It seems that changing a column to be an identity while preserving data is a huge difficulty.
回答1:
SET IDENTITY_INSERT only works for INSERTS and that error is not specific to SQL Azure. You'll get the same error on SQL Server/Express
to go around the issue, SET IDENTITY_INSERT to ON, reinsert all the column values from the existing row whose identity value you want to replace with a new value, SET IDENTITY_INSERT OFF, then delete the previous row.
回答2:
I found this Possible solution from Herve Roggero who basically gives a way of turning off the ID and then adding the rows, then turning ID back on.
来源:https://stackoverflow.com/questions/9214316/how-do-you-update-an-identity-column-in-sql-azure-is-it-possible