How do I override the identity
column in MSSQL? I tried :
SET IDENTITY_INSERT GeoCountry ON UPDATE GeoCountry SET CountryID = 18 WHERE CountryID = 250
But I get back a
Line 2: Cannot update identity column 'CountryID'.
Steps for updating existing identity column valuesRemove all the foreign key constraints referencing the identity column. Copy all the records from the identity table and insert it to a staging table. Now, switch ON IDENTITY_INSERT for the identity table to allow inserting values to the identity Column.
Identity field is usually used as a primary key. When you insert a new record into your table, this field automatically assigns an incremented value from the previous entry. Usually, you can't insert your own value to this field.
You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.
The error message clearly states that you cannot explicitly insert an identify value unless you specify a column list along with the INSERT statement, and the IDENTITY_INSERT property for the Widget table is set to ON.
You are trying to perform an update, not inserting new rows.
In order to do that, you will need to set identity_insert
ON and copy the row you want to update to a new row with the new ID value, then delete the old row (assuming no FK is referencing it)
Something along the lines of:
set identity_insert GeoCountry on go insert into GeoCountry (all columns including IDentity column) select 18, (all columns except IDentity column) from GeoCountry where CountryID = 250 -- Delete will only work if no referencing FK's delete GeoCountry where CountryID = 250 set identity_insert GeoCountry off go
[Given that you are trying to update it, that would suggest it is still in use (i.e. by referencing FK's) and that makes things more complicated...]
You cannot update the Identity Column in SQL Server. You have to delete the original record, then Insert the record with the Identity value because there is no support for updating an identity value.
set Identity_Insert [ColumnName] On Insert identity and additional information previously stored in that record set Identity_Insert [ColumnName] Off
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With