May 022011
 

I love identity columns in database. They make great primary key for almost any table. Only situation where I hate them is when I need to import data with foreign keys. You see, you cannot manually define identity column. Or can you?

Let’s imagine SQL Server table (named SomeTable) with two columns. First one will be Id (int, identity and primary key) and second one will be SomeText (nvarchar). Then let’s try to insert some data:

INSERT INTO SomeTable(Id, SomeText) VALUES(1, 'Some text');
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'LookupDiagnosis' when IDENTITY_INSERT is set to OFF.

Like all good error messages, this one already offers solution. We need to manipulate IDENTITY_INSERT option. Let’s try again:

SET IDENTITY_INSERT SomeTable ON
INSERT INTO SomeTable(Id, SomeText) VALUES(1, 'Some text');
SET IDENTITY_INSERT SomeTable OFF

With this little trick importing data with identity columns becomes much easier.

P.S. Just remember that you cannot have IDENTITY_INSERT set on more than one table at a time.

P.P.S. This option is also great for filling gaps left in identity column by deleted rows or canceled transactions.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>