views:

57

answers:

3

I have a deleted file archive database that stores the ID of the file that was deleted, I want the admin to be able to restore the file (as well as the same ID for linking files). I do not want to take identity_insert off the entire table, as the increment by one works great. In my insert to TBL_Content store procedure I have something like this

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

But I keep getting the same error "Cannot insert explicit value for identity column in table 'TBL_Content' when IDENTITY_INSERT is set to OFF."

Any help?

+2  A: 

I believe it needs to be done in a single query batch. Basically, the GO statements are breaking your commands into multiple batches and that is causing the issue. Change it to this:

SET IDENTITY_INSERT tbl_content ON
/* GO */

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO
NYSystemsAnalyst
+3  A: 

Shouldn't you be setting identity_Insert ON, inserting the records and then turning it back off?

Like this:

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
Abe Miessler
works thank you, though I can only give one answer
Spooks
+2  A: 

Should you instead be setting the identity insert to on within the stored procedure? It looks like you're setting it to on only when changing the stored procedure, not when actually calling it. Try:

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

SET IDENTITY_INSERT tbl_content ON

...insert command...

SET IDENTITY_INSERT tbl_content OFF
GO
David
Works thank you
Spooks
Abe Miessler beat me to the punch by less than a minute, too :) I need to get quicker!
David
These fingers are on fire son!!!! You got the check mark tho :(
Abe Miessler
There, I upped yours by one just to give you some reputation, since I kind of feel bad :)
David
haha aww thanks
Abe Miessler