SQL Server error: “Cannot insert explicit value fo

2019-08-21 04:06发布

问题:

I REALLY review several times, that's the reason I am asking; looking for guidance...

I have one table, as the script below. Then, I set IDENTITY_INSERT ON. Then I try to do an insert select, (I NEED the very same ids)

I keep getting this error:

Msg 544, Level 16, State 1, Line 2
Cannot insert explicit value for identity column in table 'Table1' when IDENTITY_INSERT is set to OFF.

Does anybody knows why? Any set up at DB level can overrule the IDENTITY_INSERT ON?

I appreciate any advice. Thanks in advance and kind regards.

Script to table:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].Table1
(
    [TableId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    [RowVersion] [timestamp] NOT NULL,
    [AddedDate] [datetime2](7) NOT NULL,
    [stuff2] [int] NOT NULL,
    [ModifiedDate] [datetime2](7) NOT NULL,
    [LastModifiedBy] [int] NOT NULL,

    CONSTRAINT [Table1_PK] 
        PRIMARY KEY CLUSTERED ([TableId] ASC)
) ON [PRIMARY]
GO

The insert statement:

SET IDENTITY_INSERT [dbo].Table1 ON;

INSERT INTO [dbo].Table1 ([TableId], [Name], [AddedDate], [stuff2], [ModifiedDate], [LastModifiedBy])
    SELECT 
        [RoleID], [Name], [AddedDate], [stuff2], [ModifiedDate], [LastModifiedBy] 
    FROM 
        [dbo].Table2

回答1:

Thank you so much @Sami, you help me to realize the right path. It turns out, you can just use, IDENTITY_INSERT to one table at time (for obvious reasons is not a thing I do often). When I did for several tables at time, I saw the error, but as the name of the tables were similar, I thought it was throwing an error because I ran the Identity_insert before on the same table, but it was because it was taken by the other table. I didn't realized until I review the Error messages one by one. :P :D

https://dba.stackexchange.com/questions/12650/why-is-identity-insert-on-only-allowed-on-one-table-at-a-time



回答2:

I had the same error, then i found out that i was inserting an explicit value while my PK is set to Is Identity = true, while my relation was 1:1..0, meaning my child table uses the PK of the Parent table. [DatabaseGenerated(DatabaseGeneratedOption.Identity)] will only work if the Is Identity = true and there is no conflict in your table.