I need to get the last inserted row in a specific table for strictly the current session. I can’t use @@IDENTITY and SCOPE_IDENTITY() as they will return the last inserted identity for ANY table. The problem with IDENT_CURRENT is that it will return the last inserted identity of a record for a specific table but for ANY session. This is a problem for me because the INSERT is called by multiple sessions, and I specifically need the identity of the last inserted record for my specific session.
Any pointers how to accomplish this?
ps. the INSERT statement is not inside a SPROC, so SPROC solutions are not viable.
Thanks
I know it’s not the answer you seem to want to hear, but the answer is to use
SCOPE_IDENTITY(). The problem you are thinking of (where it will be for any table) is why we useSCOPE_IDENTITY()instead of@@IDENTITY. Consider the case where you have a table with anIDENTITYcolumn, and an insert trigger on that table that itself inserts into a table with anIDENTITYcolumn.Now, your situation is that you want a reliable way to retrieve the ID after an insert.
SCOPE_IDENTITY()gives you that, since it is restricted to your scope, while@@IDENTITYis not restricted to your scope (meaning it will grab the lastIDENTITYissued, which happened in the triggers’ scope, not your scope:Results:
Note that neither
SCOPE_IDENTITY()nor@@IDENTITYshould be used in the case where you insert multiple rows. The way to do this would be to use theOUTPUTclause. First let’s drop the trigger:Now let’s test a multi-row insert:
Results:
If you have conditional inserts, there is no difference. Keeping the tables we have, let’s try this code twice:
Result:
Let’s try it again with
N'Foo':Results:
If it’s more complex than that (e.g. you may insert into more than one table), you can do something like:
I’m not sure why you think this doesn’t work, and I’m not sure why I have to go to this length to convince you that it does. Again, if you show an example where this doesn’t work (or what “ANY table” you think might interfere), we might be able to comment. As it stands it sounds like your opinion of
SCOPE_IDENTITY()is based on something you’ve heard about@@IDENTITY. These assumptions are quite easy to prove or disprove yourself.As an aside,
IDENT_CURRENTshould not even be mentioned in this conversation. It is not safe to use for concurrent activity at all, and you should pretend that you’ve never heard of it as far as I’m concerned. You should also consider the same for@@IDENTITY– I can’t think of a valid use for it unless you really do want to capture, from outside of the trigger, theIDENTITYgenerated inside a trigger.