我有这个sql表
CREATE TABLE Notes(
NoteID [int] IDENTITY(1,1) NOT NULL,
NoteTitle [nvarchar](255) NULL,
NoteDescription [nvarchar](4000) NULL
) CONSTRAINT [PK_Notes] PRIMARY KEY CLUSTERED
(
NoteID ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我想从包含NoteID的临时表中复制记录(使用sql查询)..
这是我的剧本:
SET IDENTITY_INSERT Notes OFF
INSERT INTO Notes (NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp
SET IDENTITY_INSERT Notes ON
使用此脚本,我收到错误:
Cannot insert explicit value for identity column in table 'Notes' when IDENTITY_INSERT is set to OFF.
是否有其他方法使用sql查询将记录插入到具有标识列的表中?
答案 0 :(得分:29)
改变<和p>周围的OFF和ON
SET IDENTITY_INSERT Notes ON
INSERT INTO Notes (NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp
SET IDENTITY_INSERT Notes OFF
答案 1 :(得分:6)
SET IDENTITY_INSERT Notes ON
INSERT INTO Notes
/*Note the column list is REQUIRED here, not optional*/
(NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp
SET IDENTITY_INSERT Notes OFF
您正在插入作为标识列的NoteId的值。 您可以像这样在表格上启用标识插入,以便您可以指定自己的标识值。
答案 2 :(得分:2)
据推测,您正在使用SQL Server(您没有说),并且误解了IDENTITY_INSERT的含义和目的。通常,不允许您显式设置IDENTITY列的值,但是通过将表的IDENTITY_INSERT设置为ON,您可以暂时允许此类插入。