Monday 12 October 2015

Difference between @@IDENTITY, SCOPE_IDENTITY() and IDENT_CURRENT() in SQL SERVER


When we set IDENTITY for a column, the column is known as AUTO INCREMENT column whose value is auto incremented by SQL Server on each insert. When we insert data into a table which has an IDENTITY column thenfor the IDENTITY column we do not insert any data manually, the data is inserted for that IDENTITY column automatically by SQL Server (depending upon the Identity Increment value).
Since the values are inserted by SQL Server, to get those value we have to use some T-SQL functions. The above three functions are used to get the last IDENTITY value produced on a connection. Since there are three functions, so the Question comes When to use which function? 
SELECT @@IDENTITY() returns 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 it is not limited to the current scope. It will return the last identity value that is either explicitly created (creatd by any trigger or user defined function).

SELECT SCOPE_IDENTITY() returns the last IDENTITY value produced on a connection and within the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY  returns 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 (not includes the identity created by any trigger or user defined function).
SELECT IDENT_CURRENT(‘tablename’) returns the last IDENTITY value produced in a table. It does not depend on any session or scope, instead it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.
So we have two scenario to compare session and scope
SessionScope
@@IDENTITYSame SessionGlobal scope value
SCOPE_IDENTITY()Same SessionLocal scope value
IDENT_CURRENT()May be differentDepends on table name passed in parameter
Conclusion:
SELECT @@IDENTITY: returns the last identity value generated for any table in the current session, across all scopes(i.e. global scope).

SELECT IDENT_CURRENT : returns the last identity value generated for any table in the current session and the current scope(i.e. local scope).

SELECT SCOPE_IDENTITY(): returns the last identity value generated for a specific table in any session and any scope(i.e. global scope).

No comments:

Post a Comment