Ошибка cannot insert explicit value for identity column in table

There are basically 2 different ways to INSERT records without having an error:

1) When the IDENTITY_INSERT is set OFF. The PRIMARY KEY «ID» MUST NOT BE PRESENT

2) When the IDENTITY_INSERT is set ON. The PRIMARY KEY «ID» MUST BE PRESENT

As per the following example from the same Table created with an IDENTITY PRIMARY KEY:

CREATE TABLE [dbo].[Persons] (    
    ID INT IDENTITY(1,1) PRIMARY KEY,
    LastName VARCHAR(40) NOT NULL,
    FirstName VARCHAR(40)
);

1) In the first example, you can insert new records into the table without getting an error when the IDENTITY_INSERT is OFF. The PRIMARY KEY «ID» MUST NOT BE PRESENT from the «INSERT INTO» Statements and a unique ID value will be added automatically:. If the ID is present from the INSERT in this case, you will get the error «Cannot insert explicit value for identify column in table…»

SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE'); 
INSERT INTO Persons (FirstName,LastName) 
VALUES ('JOE','BROWN');

OUTPUT of TABLE [dbo].[Persons] will be:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE

2) In the Second example, you can insert new records into the table without getting an error when the IDENTITY_INSERT is ON. The PRIMARY KEY «ID» MUST BE PRESENT from the «INSERT INTO» Statements as long as the ID value does not already exist: If the ID is NOT present from the INSERT in this case, you will get the error «Explicit value must be specified for identity column table…»

SET IDENTITY_INSERT [dbo].[Persons] ON;
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (5,'JOHN','WHITE'); 
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (3,'JACK','BLACK'); 

OUTPUT of TABLE [dbo].[Persons] will be:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE
3     BLACK      JACK
5     WHITE      JOHN

SQL Server 2019 on Windows SQL Server 2019 on Linux SQL Server 2016 Service Pack 2 SQL Server 2016 Developer — duplicate (do not use) SQL Server 2016 Enterprise — duplicate (do not use) SQL Server 2016 Enterprise Core — duplicate (do not use) SQL Server 2016 Standard — duplicate (do not use) SQL Server 2017 on Linux SQL Server 2017 on Windows More…Less

Symptoms

Assume that you use INSERT EXEC statement to insert a row that contains an explicit identity value into a table that has IDENTITY column and IDENTITY_INSERT is OFF by default in Microsoft SQL Server. You notice that the INSERT EXEC statement doesn’t work correctly. The expected behavior is that the statement fails and returns the following error message:

Cannot insert explicit value for identity column in table ‘<TableName>’ when IDENTITY_INSERT is set to OFF

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

Resolution

This issue is fixed in the following cumulative updates for SQL Server:

  • Cumulative Update 6 for SQL Server 2019

  • Cumulative Update 22 for SQL Server 2017

  • Cumulative Update 14 for SQL Server 2016 SP2

About cumulative updates for SQL Server:

Each new cumulative update for SQL Server contains all the hotfixes and all the security fixes that were included with the previous cumulative update. Check out the latest cumulative updates for SQL Server:

  • Latest cumulative update for SQL Server 2019

  • Latest cumulative update for SQL Server 2017

  • Latest cumulative update for SQL Server 2016

References

Learn about the terminology that Microsoft uses to describe software updates.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

The primary key column is often set to auto-increment when constructing a SQL Server database. The IDENTITY limit is set on for the primary key column to do this. The starting location and step of increment are transferred to the IDENTITY column as parameters. Then whenever a new record is added, and the identity insert is set to OFF, the value of the IDENTITY column is increased by the pre-defined step normally a number. Moreover, the IDENTITY INSERT property is set to ON only for one table in a single session.

In this article, we will discuss the error “Cannot insert explicit value for identity column in table <table name> when IDENTITY_INSERT is set to OFF” as shown below.

Turning the “IDENTITY INSERT OFF”, and inserting data without “PRIMARY KEY ID” into insert statement

The error arises when the user has set “identity_insert” to “OFF”. Then tries to insert data into the primary key column of the table explicitly. This can be explained using the example below.

Database and table creation:

First, create a database named “appuals”.

Creating a database named “appuals”.

Create a table named “person” using the following code. Built table using a “PRIMARY KEY IDENTITY”

CREATE TABLE person
  (
     ID INT IDENTITY (1, 1),
     first_name VARCHAR(MAX) ,
     last_name VARCHAR(MAX)
  )

Creating a table named “person”

Syntax for setting “identity_insert off | on”:

The “set identity_insert off | on” will help us resolve this error. The correct syntax for this statement is as below.

SET IDENTITY_INSERT <database name> . <schema name>. <table name> { OFF | ON }

Whereas the first argument <database name> is the name of the database in which the table is located. The second argument <schema name> shows is the schema to which that table belongs whose identity value has to be set to ON or OFF. The third argument <table name> is the table with the identity column.

There are fundamentally two different ways of data insertion into the table without error. These are considered as the solution to this error and are discussed below.

Error 1:  Set identity_insert OFF

In the first case, we will insert data into the table with the “IDENTITY INSERT” set to “OFF”. So, if the ID is present into the INSERT statement, you will get the error “Cannot insert explicit value for identity column in table ‘person’ when IDENTITY_INSERT is set to OFF”.

Execute the following code in the query tab.

 set identity_insert person off;
 insert into person(ID,first_name,last_name)
 values(3,'Sadia','Majeed'),
 (4,'Michel','Ronald')

The output will be like this.

The error arises due to turning the “IDENTITY INSERT OFF”, and inserting data with “PRIMARY KEY ID” into insert statement

Solution:

When turning the “IDENTITY INSERT OFF”, the “PRIMARY KEY ID” MUST NOT be PRESENT into the insert statement

Now execute the following code in the query tab

 set identity_insert person off;
 insert into person(first_name,last_name)
 values('Sadia','Majeed'),
 ('Michel','Ronald')

Turning the “IDENTITY INSERT OFF”, and inserting data without “PRIMARY KEY ID” into insert statement

This will insert data into the table without an error. Moreover, The PRIMARY KEY ID is not required to be inserted by the user, rather it will add unique ID value automatically as seen in the figure below.

Error 2:  Set identity_insert ON

In the second case, we will insert data into the table with the “IDENTITY INSERT” set to “ON”. So, if the ID is not present into the INSERT statement, you will get the error ” Msg 545, Level 16, State 1, Line 17. The explicit value must be specified for identity column in table ‘person’ either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column”.

The error arises due to inserting the data into the table with the “IDENTITY INSERT” set to “ON”. So PRIMARY KEY ID is explicitly required to be inserted by the user

Solution:

When turning the “IDENTITY INSERT ON” the “PRIMARY KEY ID” must be present in the insert statement.

Execute the following code in the query tab

 set identity_insert person on;
 insert into person(ID,first_name,last_name)
 values(5,'Jack','black'),
 (6,'john','Wicky')

Inserting data into the table with the “IDENTITY INSERT” set to “ON” and with primary key id in the insert statement.

This will insert data into the table without an error. Thus The PRIMARY KEY ID is explicitly required to be inserted by the user. Also, it will not add unique ID value automatically as seen in the figure below.

If you “SET IDENTITY INSERT ON”, it will remain on for the whole session. Thus you can add as many records as you want once this has been set. This also refers only to the session where it is enabled. So if you open another query tab you need to turn it ON again for that query window.

Photo of Muhammad Ussama

Muhammad Ussama

Sam is a First Line Support Engineer in Network Rail. He loves to play around & tinker with smartphones. He has a strong background and extensive experience in troubleshooting and configuring Android. He’s our go-to guy when it comes to smartphones because he always has a trick or two up his sleeve. In his spare time, he likes to listen to music & binge-watch Netflix.

  • Remove From My Forums
  • Question

  • I am writing a program to import data across from one database to another. I need to be able to make it use the current ID numbers or else the relations will be broken.

    I keep getting:

    Cannot insert explicit value for identity column in table ‘mytable’ when IDENTITY_INSERT is set to OFF.

    I have opened up SQL Server Management Studio created a new query with:

    SET IDENTITY_INSERT [BMSSUNRISE].[dbo].[SystemInventory] ON
    GO

    this results in success but the program still fails, I have tested the Insert SQL statement in the SQL Studio tool and included the above line in front of it and it works.

    MY QUESTION, how do I get VB.NET2005 to set this option on?

    I have tried to place that line above in the insert command of the table adapter but it comes up with an error saying that SET is not supported. There must be a way to be able to «enable» this using the dynamic classes that a generated.

    Any help is muchly appreciated, thankyou.

    Regards,

    Michael Proctor

Answers

  • Have you tried using an SqlCommand object, and executing the statement as SQL?

    There’s an example of how to do this in the following article:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnhcvs04/html/vs04i1.asp

    Here’s a code snippet from the article:

    dap1 = New SqlClient.SqlDataAdapter _
    ("SELECT ShipperID, CompanyName, Phone " &amp; _
    "FROM Shippers", SqlConnection1)
    dap1.InsertCommand = New SqlClient.SqlCommand _
    ("SET IDENTITY_INSERT Shippers ON ")
    dap1.InsertCommand.CommandText &amp;= _
    "INSERT INTO Shippers " &amp; _
    "(ShipperID, CompanyName, Phone) " &amp; _
    "VALUES (@ShipperID, @CompanyName, @Phone)"
    dap1.InsertCommand.Connection = SqlConnection1

    Dim prm1 As SqlClient.SqlParameter = _
    dap1.InsertCommand.Parameters.Add _
    ("@ShipperID", SqlDbType.Int)
    prm1.SourceColumn = "ShipperID"
    prm1.SourceVersion = DataRowVersion.Current
    Dim prm2 As SqlClient.SqlParameter = _
    dap1.InsertCommand.Parameters.Add _
    ("@CompanyName", SqlDbType.NVarChar, 40)
    prm2.SourceColumn = "CompanyName"
    Dim prm3 As SqlClient.SqlParameter = _
    dap1.InsertCommand.Parameters.Add _
    ("@Phone", SqlDbType.NVarChar, 24)
    prm3.SourceColumn = "Phone"

  • Thanks for your suggestions Christopher, I completed my project tonight YAY!

    In the end the opening a connection and running my SQL statement then the Update method works 100% of the time even on tables with over 200,000+ records so it seems that the connection does stay pinned up during the update method :)

    Funny you should say about the Upsizing Wizard, although I am sure it does a great job on some databases unfortunately it doesn’t do so well on ours. It had major issues with dates fields not being of SQL type and also problems with Queries as i have VBA functions in them.

    In the end a custom program to transpose the data into SQL valid data seemed to be my only answer (however MSFT did suggest SSIS which I looked into and did trial, it would have worked also as you can customise it’s transfer of data, however I had already completed over 50% of my project so just kept going)

    Pity Microsoft don’t have a property or method to allow this simply from the TableAdapter, however I had an idea (if I had to do this again) which is to overload the Update Method and have an additional parameter of IDENTITYINSERT as boolean and if so open the connection pass the SQL state then run the MS Update method and close it up. Then you would have to worry about coding each time you run the Update.

    Anyways acheived what I needed and again thanks for your assistance.

Working with EF Core 5.0.0-rc2.20475.6, migrated an old EF 6 .NET project.
I used the scaffolding command to generate the models, it worked and a part of the models are like the following example:

public class Betrieb {
    public virtual ICollection<Tagesinkassos> Tagesinkassi { get; set; }
    // many other properties and collections
}

public class Tagesinkassos {
    public long Id { get; set; }
    // other properties
    public virtual TagesinkassosTagesinkasso TagesinkassosTagesinkasso { get; set; }
    public virtual TagesinkassosPostagesinkasso TagesinkassosPostagesinkasso { get; set; }
    public virtual Betrieb Betrieb { get; set; }
}
public class TagesinkassosPostagesinkasso {
    public long Id { get; set; }
    // other properties
    public virtual Tagesinkassos IdNavigation { get; set; }
}
public class TagesinkassosTagesinkasso {
    public long Id { get; set; }
    // other properties
    public virtual Tagesinkassos IdNavigation { get; set; }
}

I moved to EF Core 5 because of the TPT, I edited the models followings

public abstract class Tagesinkassos {
    public long Id { get; set; }
    // other properties
    public virtual Betrieb Betrieb { get; set; }
}
public class TagesinkassosPostagesinkasso : Tagesinkassos {
    // other properties
}
public class TagesinkassosTagesinkasso : Tagesinkassos {
    // other properties
}

Loading data always works.
Update items already present in the Betrieb.Tagesinkassi collection also always works.
If I try to insert a new one, I get the error in the title Cannot insert explicit value for identity column in table 'Tagesinkassos' when IDENTITY_INSERT is set to OFF

I checked the database. The column Tagesinkassos.Id has the Identity Specifcation set to YES. The ids of TagesinkassosPostagesinkasso and TagesinkassosTagesinkasso have the Identity Specifcation set to NO.

Tryied to change from ON to OFF or viceversa, but it tells me that the tables have to de dropped and recreated, I can’t do it.
Is there a way to use the TPT model or do I have to keep the generated one?

  • Ошибка cannot get при запуске browser sync
  • Ошибка cannot find signatures with metadata for snap
  • Ошибка cannot find adb fastboot
  • Ошибка cannot find a valid baseurl for repo base
  • Ошибка cannot find 800x600x32 video mode скачать патч