Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将记录插入到具有标识列的SQL表中_Sql - Fatal编程技术网

将记录插入到具有标识列的SQL表中

将记录插入到具有标识列的SQL表中,sql,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_NO

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

更改开关

SET IDENTITY_INSERT Notes ON

INSERT INTO Notes (NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp

SET IDENTITY_INSERT Notes OFF

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

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插入值。
您可以像这样在表上打开identity insert,以便指定自己的标识值。

hmmm,谢谢@oldpro。。我想我确实误解了身份插入的目的。真可耻。。但是,让我再次尝试将其设置为onstanks@astander。当我尝试此操作时,我遇到了另一个错误:“提供的值的列名或数量与表定义不匹配。”!别提我的评论,我做了一件愚蠢的事,我提到的错误是因为我的脚本的另一行。。不管怎样,改变开关确实解决了我的问题,谢谢。如果我想在Notes表中添加新列时保护我的查询呢。它不会复制新创建的列的数据,因为查询中没有提到它。