26

我有这个 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 查询向具有标识列的表中插入记录?

4

3 回答 3

41

改变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
于 2013-05-27T05:47:20.060 回答
8
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 插入值。您可以像这样在表上打开身份插入,以便您可以指定自己的身份值。

于 2013-05-27T06:00:02.917 回答
3

大概您正在使用 SQL Server(您没有说)并且误解了IDENTITY_INSERT的含义和目的。通常,不允许显式设置 IDENTITY 列的值,但通过将表的 IDENTITY_INSERT 设置为 ON,您可以临时允许此类插入。

于 2013-05-27T05:50:25.533 回答