I know Scope_Identity()
, Identity()
, @@Identity
, and Ident_Current()
all get the value of the identity column, but I woul
Good question.
@@IDENTITY
: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT
, and the trigger executes another INSERT
statement).
SCOPE_IDENTITY()
: returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).
IDENT_CURRENT()
: returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT
, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).
IDENTITY()
: used when declaring a column in a table as an identity column.
For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.
To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY()
.