After much research I am a little confused by which identity tracker I should use in sql.
From what I understand scope_identity will give me the last id updated from any table and ident_current will will return the last id from a specified table.
So given that information it would seem to me the best version to use (if you know which table you will be updating) is ident_current. Yet, upon reading it seems most people prefer to use scope_identity. What is the reasoning behind this and is there a flaw in my logic?
See this blogpost for your answer in detail. Scope_identity will never return identities due to inserts done by triggers. It wont be a great idea to use ident_current in a world of change where tablenames are changed..like in a dev env.
From what I've read scope_identity() should be the right answer, however it looks like there is a bug in SQL 2005 and SQL 2008 that can come into play if your insert results in a parallel query plan.
Take a look at the following articles for more details:
@@IDENTITY vs SCOPE_IDENTITY() vs IDENT_CURRENT
- Retrieve Last Inserted Identity of RecordArticle: Six reasons you should be nervous about parallelism
See section titled: 1. #328811, "
SCOPE_IDENTITY()
sometimes returns incorrect value"In that case you need to write the table name, what happens if you decide to change the table name? You then also must not forget to update your code to reflect that. I always use SCOPE_IDENTITY unless I need the ID from the insert that happens in a trigger then I will use @@IDENTITY
Also the bigger difference is that IDENT_CURRENT will give you the identity from another process that did the insert (in other words last generated identity value from any user) so if you do an insert and then someone does an insert before you do a SELECT IDENT_CURRENT you will get that other person's identity value
See also 6 Different Ways To Get The Current Identity Value which has some code explaining what happens when you put triggers on the table
The theory says: To be aware of race conditions and to do not care about inserts inside triggers, you should be using
SCOPE_IDENTITY()
BUT ... there are know bugs on SCOPE_IDENTITY() (and @@IDENTITY) as is mentioned and linked on other anwsers. Here are the workarounds from Microsoft that takes into account this bugs.Below the most relevant part from the article. It uses
output
insert's clause:SELECT IDENT_CURRENT
-- as you said will give you the table specific last inserted identity value. There are issues associated with this, one the user need to have permission to see the metadata otherwise it returns NULL and second you are hardcoding the name of the table , which will cause a problem in case the table name changes.The best practice is to use Scope_Identity together with a variable ...Look the following example
Thus by making use of variable and scope_identity next to the insert statement of interest, you can make sure that you are getting the right identity from the right table. Enjoy