Turn off Identity Whilst Inserting SQL Table Row

Inserting table rows including the index idents will give an error similar to:

Cannot insert explicit value for identity 
column in table TableName when IDENTITY_INSERT is 
set to OFF.

I was copying the contents of a database table from one installation of DotNetNuke to another.

Wishing to maintain the table structure, parent and child references meant that to best recreate and copy the table I should maintain the existing index identify values.

The table used the table unique identity index to create a parent and child relationship between some of the rows.

To export the table I was able to select all of the table content and display it as a table.

The table of data could then be copied into an editor (Geany) to add the necessary insert SQL.

To properly maintain the table data and allow a true reproduction the interlinking between the rows must be maintained. To adhesive this the index ident must be imported.

A table will automatically assign the route ident when the route is inserted. If the field is included as part of the insert statement the insert will fail with an error.

To overcome the block on the insert into the ident field i turned off the restriction at the start of my SQL insert and restore it again afterwards.

For a table with an orienting set on one of the fields performing a simple insert will fail beaches the identity field doesn’t permit is valid to be set.

To overcome this I top and tailed the insert statements with identity on and off

SET IDENTITY_INSERT GalleryAlbum ON

Insert of table rows SQL

SET IDENTITY_INSERT GalleryAlbum OFF