Using Autonumbering in Access - INSERT statements

Smashery picture Smashery · Apr 21, 2009 · Viewed 33.9k times · Source

I'm having trouble running an INSERT statement where there's an autonumber as the PK field. I have an Auto-incrementing long as the Primary Key, and then 4 fields of type double; and yet Access (using ADO) seems to want five values for the insert statement.

INSERT INTO [MY_TABLE] VALUES (1.0, 2.0, 3.0, 4.0);
>> Error: Number of query values and destinations fields are not the same.

INSERT INTO [MY_TABLE] VALUE (1, 1.0, 2.0, 3.0, 4.0);
>> Success!!

How do I use Autonumbering to actually autonumber?

Answer

Frederik Gheysels picture Frederik Gheysels · Apr 21, 2009

If you do not want to provide values for all columns that exists in your table, you've to specify the columns that you want to insert. (Which is logical, otherwise how should access, or any other DB, know for which columns you're providing a value)?

So, what you have to do is this:

INSERT INTO MyTable ( Column2, Column3, Column4) VALUES ( 1, 2, 3 )

Also , be sure that you omit the Primary Key column (which is the autonumber field). Then, Access will set it to the next value by itself.

You can then retrieve the primary-key value of the newly inserted record by executing a

SELECT @@identity FROM MyTable

statement.