I run into situation where i have to insert explicit value for identity column and run into following error, which is expected. Incase you run into similar situation here is the solution to insert value into Identity column in SQL Server.
Error: Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.
Cause of error: Trying to insert record including ID field where ID field is IDENTITY Column.
Solution:
1) Make sure that you are in situation where you really want to insert ID, If that is not the requirement than simply remove ID field from your insert statement and try to execute the insert statement again.
2) Since i was sure that i want to insert ID in Identity column, here is solution...
SET IDENTITY_INSERT YourTableName ON
INSERT INTO YourTableName
(IDENTITY Column, Column1...ColumnN)
VALUES
(IDENTITY Value, Value1, ...., ValueN)
SET IDENTITY_INSERT YourTableName OFF
Note:
Make sure that your insert statement does include all column name list, otherwise you will run into this error.
Error:
Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'Users' can only be specified when a column list is used and IDENTITY_INSERT is ON.
VALUES
(IDENTITY Value, Value1, ...., ValueN)
Correct Insert Statement
(IDENTITY Column, Column1...ColumnN)
VALUES
(IDENTITY Value, Value1, ...., ValueN)
No comments:
Post a Comment