IDENTITY_INSERT 被设置为 OFF?

3
这是我的数据库脚本,
CREATE TABLE [dbo].[MyTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](25) NULL,
[Name] [nvarchar](25) NULL,
[dob] [date] NULL ,
 CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED 
  (
[ID] ASC
  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,     
  ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
   ) ON [PRIMARY]

当我插入时,我遇到了这个错误。
Cannot insert explicit value for identity column in table 'MyTable' when   
IDENTITY_INSERT is set to OFF.

我该怎样解决这个问题?

可能是重复的问题 - https://dev59.com/iXM_5IYBdhLWcg3wiDyA - Maximus
2个回答

13

在插入数据时,您试图为标识列指定显式值,而不是让数据库为您创建一个。

您正在执行类似以下操作:

insert into MyTable (Id, Code, Name, dob) VALUES (1, 'XXX', 'xxx', 'xxx', somedate)

而不是

insert into MyTable(Code, Name, dob) VALUES ('xxx', 'xxx', somedate)

8

根据Rafeel的建议,您不需要在Identity列中显式insert值。但是,如果您已经删除了一行,并且想要一行具有相同的ID值,则可以执行以下操作:

SET IDENTITY_INSERT MyTable ON

insert into MyTable (Id, Code, Name, dob) 
VALUES (OldIdValue, 'XXX', 'xxx', 'xxx', somedate)

SET IDENTITY_INSERT MyTable OFF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接