Possible Duplicate:
Best way to get identity of inserted row?
So lets imagine I am building an Auction database for the first time using SQL Server 2012.
Someone creates an auction listing and this is inserted into the database and given a new unique AuctionID. Along with the insertion of the auction, there are many other pieces of data that need to be stored and associated with the auction e.g. images, product properties, etc.
There is a table that holds basic Auction data, and then other tables to store all the other pieces of information that allow for a many-to-many relationship with the Auction.
Now then, in the other tables that hold data about the Auction there would at least be one column that contains the AuctionID and one other column that holds some other info e.g. product specifications.
My way of achieving this (so far) is to first do the insertion of the basic Auction listing and let the database give it a new AuctionID. Fantastic. Next I do this:
SELECT TOP 1 AuctionID FROM Auction
ORDER BY Timestamp DESC
This should return the AuctionID that was last inserted, and if run immediately after the insertion should be the correct one.
I then take this AuctionID, and use that value when inserting the additional information pieces into the other table therefore creating a many-to-many relationship. Viola!
However, is this the correct way to do this when there are millions of transactions happening at the same time so theoretically insertions might be happening within millisecods of each other. Between an insertion taking place, and me retreiving the last inserted AuctionID, I could end up with the wrong AuctionID.
Can anyone please be kind enough to excuse my newbie post and suggest the best way to do this? I have many SQL books in front of me but can't find anything relating to this.