SQL Server IDENTITY_INSERT已启用,但INSERT查询会抱怨它未启用

时间:2015-02-11 17:43:46

标签: sql sql-server insert

我正在使用MigratorDotNet为应用程序编写一个迁移,并且在运行了数千个类似的插入之后,SQL服务器抱怨:

  [migrate] SET IDENTITY_INSERT TimeOfDay ON
  [migrate] INSERT INTO TimeOfDay (id) VALUES ('312491')
  [migrate] [Warning] Cannot insert explicit value for identity column in table 'TimeOfDay' when IDENTITY_INSERT is set to OFF.
  [migrate] SET IDENTITY_INSERT TimeOfDay OFF

就在上面,有类似的插入成功:

  [migrate] SET IDENTITY_INSERT TimeOfDay ON
  [migrate] INSERT INTO TimeOfDay (id) VALUES ('312485')
  [migrate] SET IDENTITY_INSERT TimeOfDay OFF
  [migrate] SET IDENTITY_INSERT TimeOfDay ON
  [migrate] INSERT INTO TimeOfDay (id) VALUES ('312486')
  [migrate] SET IDENTITY_INSERT TimeOfDay OFF
  [migrate] SET IDENTITY_INSERT StartAndEndTime ON
  [migrate] INSERT INTO StartAndEndTime (id, Start, Finish) VALUES ('156190', '312485', '312486')
  [migrate] SET IDENTITY_INSERT StartAndEndTime OFF

TimeOfDay表中的其他列默认为null,插入是将它们设置为null。

使用Migrator.Providers.TransformationProvider.ExecuteNonQuery执行查询。 有谁知道这里发生了什么?

1 个答案:

答案 0 :(得分:0)

对此的解决方案似乎是在SET IDENTITY_INSERT的同一次调用中使用INSERT操作调用ExecuteNonQuery命令。以前,它们是在ExecuteNonQuery的单独调用中完成的,正如Aaron Bertrand所说,可能会失败,因为连接可能会在调用之间重置。