Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update values in identity column

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'.

like image 972
lowerkey Avatar asked Oct 16 '10 02:10

lowerkey


People also ask

How do you update identity column values?

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.

Can we insert value in 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.

How do you alter a column with identity?

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.

Can we insert value in identity column in SQL Server?

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.


2 Answers

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...]

like image 168
Mitch Wheat Avatar answered Oct 13 '22 09:10

Mitch Wheat


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

like image 45
Gary J. Avatar answered Oct 13 '22 10:10

Gary J.