Wednesday, November 10, 2010

Difference between SCOPE_IDENTITY vs @@IDENTITY vs IDENT_CURRENT

SCOPE_IDENTITY, IDENT_CURRENT,@@IDENTITY functions return last-generated identity values.

In most of our application scenario, we need to get latest inserted row information through SQL query. And for that, we have multiple options like:

# @@IDENTITY
# SCOPE_IDENTITY
# IDENT_CURRENT


All three functions return last-generated identity values. However, the scope and session on which last is defined in each of these functions differ.

Compare

@@IDENTITY

It returns the last identity value generated for any table in the current session, across all scopes.

Let me explain this... suppose we create an insert trigger on table
which inserts a row in another table with generate an identity
column, then @@IDENTITY returns that identity record which is
created by trigger.


SCOPE_IDENTITY

It returns the last identity value generated for any table in the
current session and the current scope.

Let me explain this... suppose we create an insert trigger on table
which inserts a row in another table with generate an identity column, then SCOPE_IDENTITY result is not affected but if a trigger or a user defined function is affected on the same table that produced the value returns that identity record then SCOPE_IDENTITY returns that identity record which is created by trigger or a user defined function.


IDENT_CURRENT

It returns the last identity value generated for a specific table in any session and any scope.

In other words, we can say it is not affected by scope and session, it only depends on a particular table and returns that table related identity value which is generated in any session or scope.

No comments: