Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert specific ID in identity field

Tags:

sql-server

Is it possible to insert specific value in identity field in a SQL table?

I deleted some rows and imported them again, but I need to insert some exceptions with exact IDs.

like image 542
okkko Avatar asked Sep 12 '16 07:09

okkko


People also ask

Can I insert value in identity column?

An explicit value for the identity column in table 'Students' can only be specified when a column list is used and IDENTITY_INSERT is ON. In simple words, the error says that since the flag IDENTITY_INSERT is off for the Id column, we cannot manually insert any values.

Can you insert a row for identity column?

The system generates an IDENTITY column value when the keyword DEFAULT is used as the insert_clause for the IDENTITY column.

How do you modify an identity column?

In any case, you cannot modify an identity column, so you have to delete the row and re-add with new identity. You cannot remove the identity property from the column (you would have to remove to column)


1 Answers

You can turn on/off inserting identity values with SET IDENTITY_INSERT On/Off:

To enable your custom values:

SET IDENTITY_INSERT TableName ON

To enable auto-values:

SET IDENTITY_INSERT TableName OFF

Note that you have to list the (non-nullable) columns explicitly if you want to insert identity values, like here:

INSERT INTO TableName (ID, Text, OtherColumns...) Values (99, 'foo', ...)

You can't omit the column-list by using this syntax:

INSERT INTO TableName Values (99,'foo')
like image 169
Tim Schmelter Avatar answered Oct 14 '22 23:10

Tim Schmelter