troubleshooting Question

get the last ID of an item added?

Avatar of pigmentarts
pigmentartsFlag for United Kingdom of Great Britain and Northern Ireland asked on
Microsoft SQL ServerWeb ServersMicrosoft SQL Server 2005
6 Comments2 Solutions854 ViewsLast Modified:
at the moment I have a query which inserts a new product into my database. after I have done this I need to know the new prodID of the item just added (the unique ID  generated by the database).

As you can see below (code)  I dont do this very efficiently at the moment , because if another user was adding at the  same time  its possible although unlikely that I could get the wrong product ID.

So my question is....... can I get the prodid of the item I have just added (see below), without have to run another query right after to find the last id?

Thank in advanced  :)  


the code.....

// ADD NEW ITEM
<cfquery name="addProduct">
    INSERT INTO products (name, productCode, description) VALUES ('#FORM.name#', '#FORM.productCode#', '#FORM.description#')
</cfquery>

//GET THE LAST ITEM ADDED
<cfquery name="getLastProdId" maxrows="1">
      SELECT prodId FROM products ORDER BY prodId DESC
</cfquery>
            
//SET ID IN A STRING
prodId = #getLastProdId.prodId#;
ASKER CERTIFIED SOLUTION
Aneesh
Database Consultant
Join our community to see this answer!
Unlock 2 Answers and 6 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros