What is the best way to get IDENTITY
of inserted row?
I know about @@IDENTITY
and IDENT_CURRENT
and SCOPE_IDENTITY
I'm saying the same thing as the other guys, so everyone's correct, I'm just trying to make it more clear.
@@IDENTITY
returns the id of the last thing that was inserted by your client's connection to the database.
Most of the time this works fine, but sometimes a trigger will go and insert a new row that you don't know about, and you'll get the ID from this new row, instead of the one you want
SCOPE_IDENTITY()
solves this problem. It returns the id of the last thing that you inserted in the SQL code you sent to the database. If triggers go and create extra rows, they won't cause the wrong value to get returned. Hooray
IDENT_CURRENT
returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.
If you want to play it safe, always use SCOPE_IDENTITY()
. If you stick with @@IDENTITY
and someone decides to add a trigger later on, all your code will break.