IDENTITY_INSERT设置为OFF-如何将其打开?


111

我有一个已删除的文件存档数据库,其中存储了已删除文件的ID,我希望管理员能够恢复该文件(以及用于链接文件的相同ID)。我不想从整个表中删除identity_insert,因为将其递增1效果很好。在我的插入TBL_Content存储过程中,我有这样的东西

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
SET IDENTITY_INSERT tbl_content ON
GO

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 
...insert command...
SET IDENTITY_INSERT tbl_content OFF

但是我不断收到同样的错误:

当IDENTITY_INSERT设置为OFF时,无法在表'TBL_Content'中为标识列插入显式值。

有什么帮助吗?

Answers:


173

您是否应该在存储过程中将标识插入设置为on?看起来您仅在更改存储过程时才将其设置为on,而不是在实际调用它时将其设置为on。尝试:

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 

SET IDENTITY_INSERT tbl_content ON

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

16

您是否应该将identity_Insert设置为ON,插入记录,然后再将其关闭?

像这样:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
SET IDENTITY_INSERT tbl_content ON
GO

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 
SET IDENTITY_INSERT tbl_content ON
...insert command...
SET IDENTITY_INSERT tbl_content OFF

14

我相信这需要在单个查询批处理中完成。基本上,GO语句将您的命令分成多个批处理,这导致了问题。更改为此:

SET IDENTITY_INSERT tbl_content ON
/* GO */

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO

1
没错 这就是重点!下一个要插入的命令批处理应以SET IDENTITY_INSERT tbl_content ON开头;再次命令。
杰特罗

9

提醒

SQL Server只允许一个表的IDENTITY_INSERT属性设置为ON。

这不起作用:

SET IDENTITY_INSERT TableA ON
SET IDENTITY_INSERT TableB ON
... INSERT ON TableA ...
... INSERT ON TableB ...
SET IDENTITY_INSERT TableA OFF
SET IDENTITY_INSERT TableB OFF

代替:

SET IDENTITY_INSERT TableA ON
... INSERT ON TableA ...
SET IDENTITY_INSERT TableA OFF
SET IDENTITY_INSERT TableB ON
... INSERT ON TableB ...
SET IDENTITY_INSERT TableB OFF


4

在查询上方添加此行

SET IDENTITY_INSERT tbl_content ON

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.