Monday, April 8, 2013

Insert Explicit Value for Identity Column in Table

When we want to insert explicit value for a column that is already set to identity and auto incrment,then we are likely to gt an error"Cannot insert explicit value for identity column in table 'IdentityTable' when IDENTITY_INSERT is set to OFF."
The trick is to enable IDENTITY_INSERT for the table.

SET IDENTITY_INSERT IdentityTable ON

INSERT IdentityTable(TheIdentity, TheValue)VALUES (3, 'First Row')

SET IDENTITY_INSERT IdentityTable OFF
 
Note:
Identity_Insert can be enabled  on only one table in database if you enable on second table .you will get error in first and we have to provide value for identity column when we use identity _insert enabled  as On.
After we insert identity as off again,sql server set identity seed as current value.

No comments :

Post a Comment