http://www.sqlservercentral.com/blogs/steve_jones/2010/04/29/a-identity-bug/

Printed 2014/04/20 10:47PM

A Identity Bug

By Steve Jones, 2010/04/29

Someone asked an interesting question recently. If they had this code:

if OBJECT_ID('aa') is not null
   drop table aa
create table aa (id int identity(1,1))
go
set identity_insert aa on
insert aa (id) select -10 union select -11
set identity_insert aa off

insert aa default values

select * from aa

drop table aa

The results look like this:

rseults_a

That doesn’t seem right. In fact, I would assume that you would have –10, –11, and 1 as the values. However it doesn’t work.  Why?

It’s a bug. This is actually listed on Connect, and marked as “resolved”, which makes me think that the code has been marked for SQL 11 and corrected.

You can change the identity value. Look at this code:

if OBJECT_ID('aa') is not null
   drop table aa
create table aa (id int identity(1,1))
go
set identity_insert aa on
insert aa (id) select 8
set identity_insert aa off

insert aa default values

select * from aa

drop table aa

It returns 8, and 9, because when you insert a specific value for the identity that is large than the current value, the current value is set to the inserted value.

I’ve used lots of identities, but never messed with negative values, so this surprised me. There’s no reason why you can’t use them, just be aware that if you start an empty table with SET IDENTITY_INSERT on, you could end up skipping the “1".


Copyright © 2002-2014 Simple Talk Publishing. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.