我在数据库中有一张表 Foo
命名 Bar
,其中有一列名为 ID
,它是主键,这个数据库存在于开发 SQL Server 上。
我正在尝试将数据从我们的生产服务器复制到开发服务器,以便我可以使用所述数据,因此我执行以下操作:
set IDENTITY_INSERT Foo.dbo.Bar ON
insert into Foo.dbo.Bar
(
ID
,Something
,Else
,Is
,Going
,Horribly
,Wrong
,With
,SQL
)
select
ID
,Something
,Else
,Is
,Going
,Horribly
,Wrong
,With
,SQL
from Production.Foo.dbo.Bar
set IDENTITY_INSERT Foo.dbo.Bar OFF
我得到了错误
Msg 8107, Level 16, State 1, Line 1
IDENTITY_INSERT is already ON for table 'Foo.dbo.Bar'. Cannot perform SET operation for table 'Foo.dbo.Bar'.
嗯..好的,所以为表打开了 IDENTITY_INSERT。所以我删除了
SET IDENTITY_INSERT Foo.dbo.Bar ON
从我的查询的顶部,然后执行它,我收到此错误:Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Bar' when IDENTITY_INSERT is set to OFF.
我可以执行
SET IDENTITY_INSERT Foo.dbo.Bar OFF
一整天,但如果我试着转动它ON
,然后 SQL Server 2012 说 IDENTITY_INSERT
已经开启。
最佳答案
有趣 - 我刚刚在我全新的 ss2012 数据库中的 4 个表中的 3 个遇到了完全相同的问题。
所以我重写了表创建脚本,用“设置身份打开”和“设置身份关闭”来括起我的插入,它可以工作。似乎 ss 一次只想处理一个表的身份,即在关闭所有其他表身份之前,您无法设置新的表身份。
像这样:
create table Employers
(
id int PRIMARY KEY IDENTITY ,
companyid nvarchar(50) not null,
companyName nvarchar(80) not null,
address nvarchar(80),
Phone nvarchar(10),
);
SET IDENTITY_INSERT employers ON;
insert into Employers(id,companyid,companyName,address,Phone)
Values
(...),
(...)
SET IDENTITY_INSERT employers OFF;
create table customers
(
...
关于sql - 无法插入显式值,因为 IDENTITY_INSERT 为 OFF,但无法将 IDENTITY_INSERT 设置为 ON,因为它已为 ON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17347946/