[DB] Getting the ID of the record you just created

Started by
2 comments, last by Optus 15 years, 12 months ago
If I use a DAO pattern, I might have method Horse createHorse(Horse horse), which does an INSERT. A Horse has an id, but the DB will automatically allocate this during the INSERT. But I want the createHorse method to return the Horseobject with it's allocated ID. I don't know if I can do the insert and then simply ask the DB for the largest ID, because what if two calls to createHorse happen at the same time from different users? It must be a standard thing... what's the answer?
Advertisement
For security reasons, you should have all DB access go through a stored procedure. I assume what ever DB you're using supports them.

DECLARE @SystemID uniqueidentifierSET @SystemID = NEWID()INSERT <your new record>SELECT @SystemID


Happy coding.
SPs aren't necessarily allowed. Plus I'm working on a quick prototype so it's not the fastest way to do things.
Depends on the database in question. In MySQL you can use the mysql_insert_id() function. In SQL Server it's scope_identity().

insert into [..] values (..); select scope_identity()/mysql_insert_id()

Both are safe in the case of simultaneous inserts.

This topic is closed to new replies.

Advertisement