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 for returns the last identity value generated for a specific table in any session and any scope (i.e., global scope).
The 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 the above example, I have created a trigger on TBL1 for the insert. The trigger will fire when we insert a value in TBL1, and it will insert a default value in TBL2.

Now see the 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 the 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 the 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. 

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...