Turning Off and On Identity Column in SQL Server

Posted April 21, 2006 at 2:05 PM by Ben Nadel

Tags: ColdFusion, SQL

I have been moving over the data from one database to another and am currently using XML files as an intermediate step. The process has been going very smoothly, and I just learned something new. I need to keep certain ID column values across the database and was worried about turning on and off identity column AND automating the XML to DB scripting. But, found a great solutions.

SET IDENTITY_INSERT tablename ON
SET IDENTITY_INSERT tablename OFF

It's wicked cool. But, it actually took me a bit to debug. I had the ON/OFF confused. I thought they were referring to the DB's insert functionality, and so, I thought I had to turn it OFF in order to insert my own values. I realize now, that it is referring to the SQL statements ability to insert identity column value, and hence, I need to turn it ON to run my scripts.

It all comes together rather nicely:

  • <!--- Update the data records. --->
  • <cfquery name="qTurnOnInsert" datasource="#DATA.Source#" username="#DATA.Username#" password="#DATA.Password#">
  • <!--- Delete the data in the table. --->
  • DELETE FROM
  • [#strTableName#]
  • ;
  •  
  • <!--- Turn on the ability insert the identity column. --->
  • SET IDENTITY_INSERT [#strTableName#] ON
  • ;
  • </cfquery>
  •  
  • <!--- Loop over the data query to add new rows. --->
  • <cfloop query="qData">
  • <!--- Inser this row. --->
  • <cfquery name="qInsert" datasource="#DATA.Source#" username="#DATA.Username#" password="#DATA.Password#">
  • INSERT INTO [#strTableName#]
  • (
  • <cfloop index="intColumn" from="1" to="#ListLen(qData.ColumnList)#" step="1">
  • <cfif (intColumn GT 1)>,</cfif>
  • [#ListGetAt( qData.ColumnList, intColumn )#]
  • </cfloop>
  • ) VALUES (
  • <cfloop index="intColumn" from="1" to="#ListLen(qData.ColumnList)#" step="1">
  • <cfif (intColumn GT 1)>,</cfif>
  • <cfqueryparam value="#qData['#ListGetAt( qData.ColumnList, intColumn )#'][qData.CurrentRow]#" cfsqltype="CF_SQL_VARCHAR" />
  • </cfloop>
  • )
  • ;
  • </cfquery>
  • </cfloop>
  •  
  • <!--- Turn off the ability insert the identity column. --->
  • <cfquery name="qTurnOffInsert" datasource="#DATA.Source#" username="#DATA.Username#" password="#DATA.Password#">
  • SET IDENTITY_INSERT [#strTableName#] OFF;
  • </cfquery>

 



Reader Comments

Mar 27, 2007 at 2:29 PM // reply »
1 Comments

MS-SQL DTS would work a lot better for data transfer. You can carry the indexes and other objects if necessary. Also alows pulling data by query and from just about any data source.


May 19, 2010 at 4:57 PM // reply »
1 Comments

Thanks for the code, this makes my job of inserting Identity values into another table that much easier.
Best,
Mike D


May 19, 2010 at 4:59 PM // reply »
11,243 Comments

@Mike,

My pleasure.


Jul 23, 2010 at 11:23 AM // reply »
2 Comments

"LET and SET statements are no longer supported" in ASP.NET


Jul 23, 2010 at 11:25 AM // reply »
11,243 Comments

@Jim,

What do you mean in ASP.NET? The "SET" command here is part of SQL. Are you referring to a specific database?


Jul 23, 2010 at 11:29 AM // reply »
2 Comments

Sorry, it works perfectly well, I just didn't execute it as a SQL statement.

cmd1.commandtext = "SET IDENTITY_INSERT dua ON"
cmd1.ExecuteNonQuery()


Jul 23, 2010 at 11:30 AM // reply »
11,243 Comments

@Jim,

Ah, no worries :) Glad you got it working now.


Oct 19, 2010 at 2:31 PM // reply »
2 Comments

I'm still getting an insert error when I have turned the identity on.

(SET IDENTITY_INSERT dao.Applications ON)-> Command(s) completed successfully.

Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Applications' when IDENTITY_INSERT is set to OFF.


Oct 19, 2010 at 2:51 PM // reply »
2 Comments

I added "GO" before and after my insert stmnts and it worked! Thanks!


Oct 20, 2010 at 9:57 AM // reply »
11,243 Comments

@Flip,

Interesting. What database system are you using?


Nov 8, 2010 at 8:59 AM // reply »
1 Comments

I have a remark (maybe trivial, maybe not) - I tried executing this via Management Studio and after this doing insert in another query editor and it kept failing. But when I pasted both into one window and executed in a single click then it worked fine - seems like the setting is rather temporary.


Dec 9, 2010 at 1:18 PM // reply »
1 Comments

How do I deal with turning Identity_Insert On with ORM? All I'm doing is creating a new entity and then calling the entitySave() method, and I get the message: "Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF."

Maybe I could insert a cfquery and explicitly turn it on before calling the entitySave method, but wouldn't that defeat the purpose of the ORM framework?


Jan 11, 2011 at 1:59 PM // reply »
1 Comments

I just keep getting
"Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF."

I am using SQL Server 2008 and executing the the script from SQL Server Management Studio


Feb 7, 2011 at 9:48 PM // reply »
1 Comments

rad!


Jun 13, 2011 at 12:47 AM // reply »
1 Comments

Thanks dude, i am confused between
(SET IDENTITY _INSERT tablename ON) or (SET IDENTITY_INSERT tablename ON) thanks.....


Oct 17, 2011 at 1:37 AM // reply »
1 Comments

how to call database function in SeaSar2


Mar 19, 2012 at 1:58 AM // reply »
1 Comments

USE AdventureWorks2008R2;
GO
-- Create tool table.
CREATE TABLE dbo.Tool(
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name VARCHAR(40) NOT NULL
)
GO
-- Inserting values into products table.
INSERT INTO dbo.Tool(Name) VALUES ('Screwdriver')
INSERT INTO dbo.Tool(Name) VALUES ('Hammer')
INSERT INTO dbo.Tool(Name) VALUES ('Saw')
INSERT INTO dbo.Tool(Name) VALUES ('Shovel')
GO

-- Create a gap in the identity values.
DELETE dbo.Tool
WHERE Name = 'Saw'
GO

SELECT *
FROM dbo.Tool
GO

-- Try to insert an explicit ID value of 3;
-- should return a warning.
INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT dbo.Tool ON
GO

-- Try to insert an explicit ID value of 3.
INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel')
GO

SELECT *
FROM dbo.Tool
GO
-- Drop products table.
DROP TABLE dbo.Tool
GO


Dec 5, 2012 at 8:19 AM // reply »
1 Comments

I have used the SET IDENTITY_INSERT feature several times when migrating data, but have always done so in an "off-line" mode. Can this feature be used while the database is online taking other requests? In other words, will the setting of IDENTITY_INSERT to ON affect only my specific session or is will it affect every insert into that table?


Mar 5, 2013 at 12:24 PM // reply »
3 Comments

Ben

Here is an ORM that works with SQL Server
https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx


May 21, 2013 at 9:25 AM // reply »
1 Comments

you are awesome..i am lucky to get this blog between such a garbage one....Thanks, Prashant



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 23, 2013 at 3:55 AM
Javascript Array Methods: Unshift(), Shift(), Push(), And Pop()
very interesting and helpful too. ... read »
May 22, 2013 at 5:35 PM
Script Tags, jQuery, And Html(), Text() And Contents()
This is still an issue 2 years later. jQuery is supposed to remediate these cross browser issues, no? I have been unable to find any statement from the jQuery team calling this behavior "by de ... read »
May 22, 2013 at 12:44 PM
Ask Ben: Query Loop Inside CFScript Tags
In cf10, if you call a function that has: local.result = {}; local.result.msg = ""; local.svc = new query(); local.svc.setSQL("SELECT * FROM..."); local.obj = local.svc.exe ... read »
May 22, 2013 at 12:29 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben: What version of Java are you using? Also, did you test users.id to see what Java reports as the data type? I wonder if it's not a Java primitive data type, but getting returned as something ... read »
May 22, 2013 at 11:47 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Dana, Awesome - so it looks like this bug was fixed in ColdFusion 10. Thanks so much for double-checking that. ... read »
May 22, 2013 at 11:37 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
When I c&p and run on cf10, I get: Selected User IDs: 1,4 User 1 selected: YES - YES User 2 selected: NO - NO User 3 selected: NO - NO User 4 selected: YES - YES User 5 selected: NO - ... read »
May 22, 2013 at 11:27 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Tom, Good thought, but no dice. Both of these still exhibit the same behavior: users.id[ users.currentRow ] users[ "id" ][ users.currentRow ] It's just something whacky happening with ... read »
May 22, 2013 at 11:07 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
Could your problem be that "users.id" is actually an ARRAY, not a single value? Perhaps try it again with "users.id[1]" (I only have CF8 here at work). ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools