Wednesday, December 11, 2013

Difference between @@IDENTITY , SCOPE_IDENTITY() , IDENT_CURRENT('TableName')

Difference between @@IDENTITY, ....



      @@IDENTITY: It returns the last IDENTITY Value produced on a connection in current session,
                              regardless of the scope of the statement that produced the value,  and
                              regardless of the table 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.
i.e If we have a trigger on a table that causes an Identity to be created in another table, then we will get the Identity that was created last i.e even if it was created in the trigger.

 --------------------------------------------------------------------------------------------------


     SELECT SCOPE_IDENTITY()
                   It returns the last IDENTITY value produced on a connection and by a statement in
         the same scope. But regardless of the table that produced the value.

          
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.


  Note:  The difference between SCOPE_IDENTITY() and @@IDENTITY  is that @@IDENTITY is
 limited only to the  current SESSION, but it is not limited to current SCOPE.
 A Session can have one or more than one Scope.
 A Scope is defined as a module eg. Like a stored procedure, function or batch.


SCOPE_IDENTITY() returns the last identity generated in the current SCOPE.

 ------------------------------------------------------------------------------------------------



SELECT IDENT_CURRENT (tablename’)
      It returns the last IDENTITY value produced in a table,
      regardless of the scope of the statement that produced the value.
      regardless of the connection that created the value, and
     
IDENT_CURRENT is not limited by any 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.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More