Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

前端 未结 22 1158
我在风中等你
我在风中等你 2020-11-22 13:56

I have the below error when I execute the following script. What is the error about, and how it can be resolved?

Insert table(OperationID,OpDescription,Filte         


        
22条回答
  •  隐瞒了意图╮
    2020-11-22 14:48

    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
    

提交回复
热议问题