SQL Server 2008 – Retrieve Last Inserted Identity of Record

From SQL Server 2005 onwards, three functions are supported for retrieving last inserted Identity value.  They are:

  1. @@IDENTITY
  2. SCOPE_IDENTITY()
  3. IDENT_CURRENT()

This article explains the purpose of each of these functions.

SELECT @@IDENTITY

25% Off CouponReturns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.

@@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY()

Returns the last identity value inserted into an IDENTITY column in the same scope. Here a scope means a stored procedure, trigger, function, or batch.

SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT(‘tablename’)

Returns the last IDENTITY value generated for a specified table or view. The last identity value generated can be for any session and any scope.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

Conclusion

To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.

Advertisements
Published in: on April 13, 2011 at 1:15 am  Comments (1)  

The URI to TrackBack this entry is: https://blackbeltreview.wordpress.com/2011/04/13/sql-server-2008-retrieve-last-inserted-identity-of-record/trackback/

RSS feed for comments on this post.

One CommentLeave a comment

  1. Great post from the blogger, I will book mark this blog.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: