I have a table in an Access database with an autonumber field.
When I delete all the records from the table, the autonumber remembers the last number.
Does A
Or without Compact and Repair when using VBA: Say your table is 'MyTable'. Make a copy of that table WITHOUT data and save it for example as 'MyTable_Template'. When you want to Truncate the table just 'DROP' the table en copy 'MyTable_Template' to 'MyTable'. Now the autoincrementfield of your 'new' table 'MyTable' will start at 1 again.
Access SQL does not have anything like TRUNCATE TABLE
.
You can use an ADO connection to execute a DDL statement which resets the autonumber field's "seed" value. So you could do this with VBA code, and not have to use compact & repair to reset the autonumber.
This example code first deletes all rows from my tblFoo table, and then resets the seed value for the id autonumber field.
Dim strSql As String
strSql = "DELETE FROM tblFoo;"
CurrentProject.Connection.Execute strSql
strSql = "ALTER TABLE tblFoo ALTER COLUMN id COUNTER (1, 1);"
CurrentProject.Connection.Execute strSql
Or without compact and repair:
Empty your table:
DELETE FROM MyTable
Alter autoincrementfield (like 'ID') to Integer:
ALTER TABLE MyTable ALTER Column ID INT;
Alter the field back to AUTOINCREMENT:
ALTER TABLE MyTable ALTER Column ID AUTOINCREMENT;
There is another way that doesn't require altering the table or compacting and repairing. It will work better for you if you have a distributed database. As of 2000, Access will accept an insert value into an autonumber field and start incrementing there. Do it in a query or in code like this.
CurrentProject.Connection.Execute "DELETE FROM Mytbl"
CurrentProject.Connection.Execute "INSERT INTO Mytbl(ID) VALUES(0)"
CurrentProject.Connection.Execute "DELETE FROM Mytbl"
Note: Put adExecuteNoRecords after the execute command for better performance. e.g. CurrentProject.Connection.Execute sql, , adExecuteNoRecords
took 1 second to find the solution at:
http://www.webmasterworld.com/databases_sql_mysql/3227574.htm
The Compact and Repair process will reset all empty table auto-increment counters to zero. So, delete all the records then:
Tools -> Database Utilities -> Compact and Repair Database
Delete all the records and then compact the database.