Recently i encountered with a problem related to fetching the identity value of a table upon insertion.In my one of the old project there was a table with identity column . In the stored procedure i had used “@@IDENTITY ” to fetch the last identity value entered into a table.After sometime i realized that i was not getting the right identity value upon insertion.After a lot of investigation i came to know that a trigger was written on this table for insert.This trigger was for insertion of record in another table with identity column.
I found that after implementation of this trigger whenever record inserted into previous table the stored procedure returns the identity value of the another table in which the record was getting inserted by the trigger.
After a lot of R&D i came to know about “SCOPE_IDENTITY()” and this one solved my problem.
The reason is – “@@IDENTITY “ will return last identity values generated in any table in the current session. So in my case this is the table which is linked with trigger.
So the concept is:
@@IDENTITY will return last identity values generated in any table in the current session. However, SCOPE_IDENTITY() returns values inserted only within the current scope .