Identity vs Scope Identity vs Ident_Current

While doing some update on an existing Store Procedure I came across a code that retrieves an Identity value.


1
2
3
4
5
6
if @@rowcount>0
begin
   select @id=scope_identity()
end
else
  select @id=0

Now let's discuss when to use Identity, Scope Identity and Ident_Current, I checked the internet and found an article from the SQL Authority. Here's a brief of what it says:

Select @@IDENTITY
It returns the identity value generated on a connection regardless of table and the scope which produce the value, it means that in case a trigger was also called from the same connection and produced an identity, this identity will be returned.

Select SCOPE_IDENTITY
It returns the identity value generated on a connection and by a statement on the same scope regardless of the table the produced the value. it will return the value that was explicitly created by the statement and will not be affected by any trigger even if it creates an identity on the same table thus limiting the scope.

Select IDENT_CURRENT(tablename)
It returns the identity value generated from a table regardless of the scope or connection, it's not limited by sope and session, as long as an identity was produced by the same table it was operating on it will return it.

As a best practice mentioned by Pinal Dave of SQL Authority it's recommended to use Scope_Identity to avoid any issues with Triggers later on.



Comments

Popular posts from this blog

Serializing JSON string to ExpandoObject

Adding an Obsolete Attribute to Class Methods in C#