insert into Student
values('1', 'joedio', 'newyark', GETDATE())
尝试运行此SQL时出现此错误消息:
只有在使用列列表并且IDENTITY_INSERT为ON时,才能指定表'Student'中标识列的显式值。
答案 0 :(得分:4)
如果您想通过查询插入主键,即使它是自动增量,那么您必须设置IDENTITY_INSERT ON
如下所示,它将允许您通过查询插入唯一值:
SET IDENTITY_INSERT [Tablename] ON;
您的查询现在将是:
SET IDENTITY_INSERT Student ON;
INSERT INTO Student VALUES('1','joedio','newyark',GETDATE());
SET IDENTITY_INSERT Student OFF;
如果您希望SQL自行管理,则默认设置为IDENTITY_INSERT OFF
并设置自动增量,表示每次插入时将新值分配给该PK列。
SET IDENTITY_INSERT Student OFF
更好地执行,因为手动插入可能会插入重复值并且会引发错误。
答案 1 :(得分:2)
如果您的表格有Identity Column
,那么您必须在插入时提及所有其他列。
只是为了样本:
INSERT INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE())
如果First列是Identity,则在插入时跳过该值:
INSERT INTO Student (Name, State, Date) VALUES('joedio','newyark',GETDATE())
如果要将值插入SQL Server
SET IDENTITY_INSERT IdentityTable ON
INSERT INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE())
SET IDENTITY_INSERT IdentityTable OFF
另请参阅链接How to Insert Values into an Identity Column in SQL Server了解更多信息。
答案 2 :(得分:0)
IDENTITY_INSERT允许将显式值插入表的标识列。 使用此查询并在'
上的表格上设置IDENTITY_INSERTSET IDENTITY_INSERT Student ON
注意:任何时候,会话中只有一个表可以将IDENTITY_INSERT属性设置为ON。
答案 3 :(得分:0)
答案 4 :(得分:0)
SET IDENTITY_INSERT Student ON;
INSERT INTO Student (RegNo, Name, Address, CreatedTime) VALUES('2','calibio','newyark',GETDATE());
SET IDENTITY_INSERT Student OFF;
答案 5 :(得分:0)
IF NOT EXISTS(SELECT * FROM Student WHERE ID = 1) THEN
SET IDENTITY_INSERT学生开;
INSERT INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE())
SET IDENTITY_INSERT学生关闭;
END
2.在SQL服务器中,当ID列为自动增量并且您没有传递ID
时INSERT INTO Student (Name, State, Date) VALUES('joedio','newyark',GETDATE())
3.在我的sql使用中可以使用
INSERT IGNORE INTO Student (ID, Name, State, Date) VALUES('1','joedio','newyark',GETDATE());
OR
INSERT IGNORE INTO Student (Name, State, Date) VALUES('joedio','newyark',GETDATE());
答案 6 :(得分:0)
试试这个:如果您真的想在IDENTITY
列中插入值,请使用其中一个给定的答案
SET IDENTITY_INSERT [Tablename] ON;
INSERT INTO [Tablename]..........
SET IDENTITY_INSERT [Tablename] OFF;
否则,只需摆脱错误,从values
INSERT INTO Student --No need to add column definition if you are inserting rest of all
VALUES('joedio', 'newyark', GETDATE()) --Error Free