Jan 16, 2015

Difference between @@IDENTITY, SELECT SCOPE_IDENTITY(), SELECT IDENT_CURRENT

SELECT @@IDENTITY: it’s responsible to returns the last identity value generated for any table in the current session, across all scopes (i.e. global scope).

SELECT SCOPE_IDENTITY(): It’s responsible to returns the last identity value generated for any table in the current session and the current scope(i.e. local scope).
SELECT IDENT_CURRENT(‘table_name’): It’s responsible to returns the last identity value generated for a specific table in any session and any scope (i.e. global scope).
Following example may clear your concept.
CREATE TABLE TBL1
(id INT IDENTITY(1,1))
CREATE TABLE TBL2(
id INT IDENTITY(100,1))
GO

CREATE TRIGGER TGR ON TBL1 FOR INSERT
AS
BEGIN
INSERT TBL2 DEFAULT VALUES
END
GO

INSERT TBL1 DEFAULT VALUES
SELECT @@IDENTITY AS FOR_IDENTITY
SELECT SCOPE_IDENTITY() AS FOR_SCOPR_IDENDITY
SELECT IDENT_CURRENT('TBL1') AS FOR_IDENT_CURRENT_TBL1
SELECT IDENT_CURRENT('TBL2') AS FOR_IDENT_CURRENT_TBL2
GO
DROP TABLE TBL1
DROP TABLE TBL2
GO


In above example, I have created a trigger on TBL1 for insert. Trigger will fire when we insert a value in TBL1 and it will insert a default value in TBL2.
Now see following result 


As per @@IDENTITY rule it returns the last identity value generated for any table in the current session, it is showing last inserted value of TBL2 although we inserted value in TBL1. It happens because after trigger fired a default value insert in TBL2 which is the last inserted identity in current session.


As per SCOPE_IDENTITY() it returns the last identity value generated for any table in the current session and the current scope so it returns TBL1 identity.


As per IDENT_CURRENT(‘table_name’) it returns the last identity value generated for a specific table in any session and any scope sot it returns TBL1 and TBL2 identity individually.