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.

我该如何解决?

4

2 回答 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)
于 2013-06-13T05:01:43.467 回答
7

正如 Rafeel 所建议的,您不需要在列中显式地指定insert值。Identity但是,如果您删除了一行并想要具有相同ID值的行。然后您可以执行以下操作:

SET IDENTITY_INSERT MyTable ON

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

SET IDENTITY_INSERT MyTable OFF
于 2013-06-13T05:46:06.473 回答