Click here to Skip to main content
15,898,792 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Difference between @@Identity And Scope_Identity? Please answer with example.
Posted

@@IDENTITY and SCOPE_IDENTITY return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
 
Share this answer
 
@@IDENTITY Returns the last identity created in the same session
where as SCOPE_IDENTITY() Returns the last identity created in the same session and the same scope. See below example for better understanding
CREATE TABLE Table1
(
  ID_col1 INT IDENTITY(1,1),
  text_col1 VARCHAR(100)
)
GO
CREATE TABLE Table2
(
  ID_col2 INT IDENTITY(5,5),
  text_col2 VARCHAR(100)
)
GO
CREATE TRIGGER InsertValuesInTable1 
ON Table1 AFTER INSERT AS
BEGIN
  INSERT INTO Table2 (text_col2) VALUES ('some text for table 2')
  INSERT INTO Table2 (text_col2) SELECT text_col1 FROM inserted
END

INSERT INTO Table1 (text_col1) VALUES ('some text for table 1')
--SEE THE DIFFERENCE HERE BY RUNNING THIS QUERY
SELECT SCOPE_IDENTITY(), @@IDENTITY
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900