I'm trying to copy identity column from one table to another, but I'm getting this error:
Cannot update identity column 'ID'.
I tried following code:
ALTER TABLE [dbo].[TableA]
ADD [ID] INT IDENTITY(20000,1), -- MAX(TableB.Id) < 20000
SET IDENTITY_INSERT TableA ON
UPDATE TableA
SET TableA.[ID] = TableB.[ID]
FROM TableA
INNER JOIN TableB ON TableB.ID = TableA.ID
SET IDENTITY_INSERT TableA OFF;
Scenario
I have two tables with 1:0-1 relationship.
TableA: Code (PK)
A,
B,
C,
D
TableB: Id (PK), Code (Unique)
1, A
2, B
3, D
Question
How to
- Create new identity column
TableA.Id
- Copy values from
TableB.Id
- Ensure new unique values for
TableA.Id
if it was missing inTableB.Id