使用IDENTITY列将记录INSERT到SQL表

Eyt*_*tch 18 sql

我有这个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]
Run Code Online (Sandbox Code Playgroud)

我想从临时表中复制包含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
Run Code Online (Sandbox Code Playgroud)

使用此脚本,我收到一个错误:

Cannot insert explicit value for identity column in table 'Notes' when IDENTITY_INSERT is set to OFF.
Run Code Online (Sandbox Code Playgroud)

有没有其他方法使用sql查询将记录插入到具有标识列的表中?

Adr*_*der 30

改变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
Run Code Online (Sandbox Code Playgroud)


小智 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
Run Code Online (Sandbox Code Playgroud)

您正在插入作为标识列的NoteId的值.您可以像这样打开表格上的标识插入,以便您可以指定自己的标识值.