@@IDENTITY
returns the most recent identity generated in the current session. In most cases you’ll probably want to use SCOPE_IDENTITY
instead, which returns the most recent identity generated in the current scope.
For example, if you insert a row into table1, but that insert fires a trigger which inserts a row into table2, then @@IDENTITY
will return the identity from table2 whereas SCOPE_IDENTITY
will return the identity from table1.
INSERT INTO my_table (my_column) VALUES ('test')
-- return the identity of the row you just inserted into my_table
-- regardless of any other inserts made by triggers etc
SELECT SCOPE_IDENTITY() AS ins_id