Wednesday 20 March 2013

What is the difference between Scope_Identity(), Identity(), @@Identity??

Most of the developers get confused in these terms:

  1. @@identity always returns the last identity value created in the same session regardless of the table that produced the value, and regardless of the scope of the statement.
  2. scope_identity() returns the identity value created in the same session and the same scope.
  3. identity() is not used to get an identity value but instead is used to create an identity in select...into statement that is declaring a column in a table as an identity column.
Here the session means the database connection.

Here is an example:
CREATE TABLE ABC(
  ID INT IDENTITY(1,1),
  Name VARCHAR(100)
)

INSERT INTO ABC (Name) VALUES ('x')
SELECT SCOPE_IDENTITY(), @@IDENTITY

Note:
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.

No comments:

Post a Comment