这是我的db脚本,
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.
我该如何解决?
答案 0 :(得分:10)
您正在尝试为标识列分配显式值,而不是在插入数据时让数据库为您创建一个。
您正在执行以下操作:
insert into MyTable (Id, Code, Name, dob) VALUES (1, 'XXX', 'xxx', 'xxx', somedate)
而不是
insert into MyTable(Code, Name, dob) VALUES ('xxx', 'xxx', somedate)
答案 1 :(得分: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