How to copy tables with IDENTITY columns

To copy the contents of a SQL Server table while preserving the Identity column is very simple, you need to turn on/off IDENTITY_INSERT to be able to set the Identity column value.  Example:

SET IDENTITY_INSERT NewTable ON
INSERT INTO NewTable(Id, Name)
SELECT Id, Name FROM OldTable
SET IDENTITY_INSERT NewTable OFF

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s