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