Travis Laborde Blog

play boxing daddy?

@@Identity

Many TSQL books show you how to use @@Identity to get the identity of the most recently added row.  Many articles online, or in magazines show the same.  What you might not know is that it is potentially a source for some very hard to trace bugs in your application.

@@Identity is potentially a very, very bad thing!  In almost every case, you should use scope_identity() instead.

Why?  @@Identity returns the most recently created identity for your current connection.  When you first use it, it might be fine.  Until someone adds a trigger.  If the trigger causes another identity to be created, guess which identity you'll get in your call to @@Identity?  Not nice.

scope_identity() is much nicer.  It gives you what you're expecting.

 

Legacy Comments


Pretsel
2003-10-29
re: @@Identity
Well shit me. Thanks for the random piece of info :D

Thats a really useful thing to know!

Darrell
2003-10-29
re: @@Identity
Yeah, we discovered this problem in an app a while back (2002 or so). As tech lead, I just went ahead and had everyone change all the procs to use scope_identity() instead of @@Identity, just in case. Especially since it took forever to track down the bug...

Jim Cheseborough
2003-11-01
re: @@Identity
Thanks a million!

Magnus
2003-11-02
re: @@Identity
Note that scope_identity() only exists in SQL Server 2000.

Pravangsu Biswas
2006-08-02
re: @@Identity
Nice posting, It is informative and excellent.

Carlos Gomez
2006-08-10
re: @@Identity
So no scope_identity() on sql2005??

Peter Wooster
2006-08-11
re: @@Identity
scope_identity() works fine in sql2005.

Ayaz Ahmad
2006-08-29
re: @@Identity
useful info regarding @@Identity. i have been using this for quite a long time. since i was not using triggers thats y no such problem occured at that time. but still thanks ;) for updating me for future developments.

aloks
2006-11-03
re: @@Identity
I want to use identity and create alphanumeric gerenrate ID e.g. By calling through Store Procedure in ASp.NEt and VB.Net using Sql Express
AA-A101
AA-A102
AA-A103
AA-A104
....
....
...
AA-A999
AA-B101
AA-B102
AA-B103
AA-B104
....
....
...
AB-A999
AB-A101
AB-A102
AB-A103
AB-A104
....
....
....

ZZ-Z999