Thursday, June 14, 2012

How to insert records on SQL Server identity column?

Scenario:


Insert records in SQL Server table with pre-defined primary key on an identity column. For instance, the the data ContactId to insert is from 11-50. How to insert the ContactId as my identity column value is 150 now? The assumption here is existing ContactId  in the range could be deleted for the new INSERT.

 Concepts:

Identity column on a table increment the value automatically for each record INSERT into the table. For example, the table "Contact" has an identity column defined on ContactID column. The column is defined to increase the max identity value by 1. This is done by specifying the increment value to 1.

The seed value lets you specify the identity column starting value. For instance, I would like to start all data from ContactId = 100.


The T-SQL table create statement looks like below:


Solution:


Turn the IDENTITY_INSERT ON to tell the server that you want to insert specific ID value. Perform the record insert. Enable the identity columns auto value by setting the IDENTITY_INSERT OFF.

Syntax:
SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }

Example:




Further references:


MSDN Table Identity Column
MSDN IDENTITY_INSERT

1 comment:

Unknown said...

I am happy to see this informative post.
Critical information corruption scenario is generally an Inconvenience for the user.
However for the ease of customers, IT professionals have launched an alternative for data damage challenges.
If a data loss issue is occured, individual has to know which application or software to utilize so as to deal with this condition of files damage.
retrieve outlook email