DelphiFAQ Home Search:

How can I obtain the next auto_increment number (before inserting a record)?

 

comments1 comments. Current rating: 4 stars (1 votes). Leave comments and/ or rate it.

Question:

How can I obtain the next auto_increment number (before inserting a record)?

Answer:

At first glance you might think to use select MAX(..) to obtain the most recent number and add one.. but that would not work if the most recent row got deleted or if there are two concurrent transactions.

It is not possible to do obtain the next value of an AUTO_INCREMENT field but you can use a little trick:

Let's say you have a table CUSTOMERS with a unique CUST_ID which is an auto_increment integer.

Change this to be a unique integer (no auto_increment) and create a second helper table CUSTOMER_IDS.

This second table has only the purpose to deliver a new unique number. In order for this to work, you'll always have to use this helper table whenever a row is inserted into your main table CUSTOMERS.

When you want to find out what the next number will be, you can use LAST_INSERT_ID() on that helper table. For more details read the documentation on this function.

http://dev.mysql.com/doc/mysql/en/Information_functions.html


Content-type: text/html

Comments:

2006-08-10, 22:03:02
anonymous from United States  
rating
'It is not possible to do obtain the next value of an AUTO_INCREMENT field'

This is not true. If you have ever used phpMyAdmin, you know it shows this information in the table structure view. You want to use this query:

SHOW TABLE STATUS LIKE 'table_name';

http://blog.jamiedo../geek/560/

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: