Sign in to follow this  
d000hg

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

Recommended Posts

d000hg    1199
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?

Share this post


Link to post
Share on other sites
LordShade    251
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 uniqueidentifier
SET @SystemID = NEWID()

INSERT <your new record>

SELECT @SystemID


Happy coding.

Share this post


Link to post
Share on other sites
Optus    422
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this