Identify fields - converting data


Author
Message
Tim Dol
Tim Dol
StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)StrataFrame User (434 reputation)
Group: Forum Members
Posts: 340, Visits: 1.4K
I need to migrate some data from an old table to a new table. The old table and new table both have an auto incremented identity field as the primary key and I need to ensure the values remain the same in the new table.

I have a business object for the old and new and have written the conversion program but when I save the new business object I get a error message 'Cannot insert explicit value for identity column in table 'ContactNew' when IDENTITY_INSERT is set to OFF.'

I tried setting the IDENTITY_INDENTITY ON before the save and IDENTITY_INSERT OFF after the same but I still get the error.

loCommand.CommandText = "SET IDENTITY_INSERT " & Me.TableNameAndSchema & " ON"

Me.ExecuteNonQuery(loCommand)

Any ideas how to solve this issue?

 

Thanks,

Tim

 


Greg McGuffey
Greg McGuffey
Strategic Support Team Member (3.4K reputation)
Group: Forum Members
Posts: 2K, Visits: 6.6K
you probably need to add the SET IDENTITY_INSERT ON and OFF to your main batch:



Dim sqlBuilder As New System.Text.StringBuilder(512)

With sqlBuilder

.AppendFormat("SET IDENTITY_INSERT {0} ON", Me.TableNameAndSchema).Append(ControlChars.NewLine)



'-- baseSQL is the actual SQL that would be executed to copy values

.Append(baseSQL)



.AppendFormat("SET IDENTITY_INSERT {0} OFF", Me.TableNameAndSchema).Append(ControlChars.NewLine)

End With



loCommand.CommandText = sqlBuilder.ToString()

Me.ExecuteNonQuery(loCommand)




I haven't tried this, but it should work.
Trent Taylor
Trent Taylor
StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)StrataFrame Developer (10K reputation)
Group: StrataFrame Developers
Posts: 6.6K, Visits: 6.9K
Greg is correct. The reason is this. When you call the ExecuteNonQuery, the connection session is only open for that one call. So when you set the IDENTITY_INSERT ON, execute, then execute the command. The IDENTITY_INSERT is back to off.



When I do this type of thing I generally like to create a stored procedure as it makes it a little easier.
GO

Merge Selected

Merge into selected topic...



Merge into merge target...



Merge into a specific topic ID...




Similar Topics

Reading This Topic

Login

Explore
Messages
Mentions
Search