Getting the ID of an INSERTed record

  • We have a table with an Identity field. Using t-sql we INSERT a record. I have seen many programmers get the new Identity value using 

    "select max(IdentityField) FROM...."

    I guess that would work in a non-multitaking environemnt but I'm concerned that that table could be updated by another process in the time between the original programmer's INSERT and their check for the Identity value.  Am I correct?

    Also, I wonder if the @@IDENTITY value, in a given t-sql batch,  gets around this problem. 

     

    TIA,

    Bill

     

  • You probably want to look into SCOPE_IDENTITY in books online.

    Here's a short description

    SCOPE_IDENTITY and @@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; @@IDENTITY is not limited to a specific scope.

    Hope this helps

     

  • Age old problem,

    How do I get the ID for the thing I just wrote.

    @@Identity immediately after the insert works but you do need a return trip from the database.

    If the Database is not going to be Mammoth I suggest using a GUID you can create that on your client then just send it along with the insert. use it for the children etc. with no return trip.

    HTH

    Tal McMahon

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply