Link to home
Start Free TrialLog in
Avatar of SteveL13
SteveL13Flag for United States of America

asked on

How create autonumber key field with a make table query

I have a make table query which when run needs to create a autonumber key field in the resulting table.  The caption for this field needs to be "Item Number".  How can I make this happen?
Avatar of mbizup
mbizup
Flag of Kazakhstan image

As far as I know, you cant do that directly.  You'll have to alter the table to add the autonumber field after running the make-table query.

In VBA, something like this:

Dim strSQL as string

' Code to run your make table query goes here
'
' Then ALTER the table...
strSQL = "ALTER TABLE YourTableName ADD ItemNumber AUTOINCREMENT(1, 1)"
CurrentDB.execute strSQL

Open in new window

Avatar of SteveL13

ASKER

ItemNumber has to have a space between the words.  

Should this then read:

strSQL = "ALTER TABLE YourTableName ADD "Item Number" AUTOINCREMENT(1, 1)"


?
If you create a table (tbl_Auto) with only a single field (ID) which is set to autonumber and no records, then you can create a query to build your destination table something like:

SELECT tbl_Auto.ID, yourTable.*
INTO yourNewTable
FROM tbl_Auto, yourTable

Since there are no records in tbl_Auto, there will be no records in this new table, but you can then use an append query to append your data to that table:

INSERT INTO yourNewTable (Field1, Field2, Field3)
SELECT Field1, Field2, Field3
FROM yourTable

either way, mbizup's or this one, will require multiple steps.
ASKER CERTIFIED SOLUTION
Avatar of mbizup
mbizup
Flag of Kazakhstan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
--->>> Try square brackets:

But as an aside, I'd recommend creating the field with no space in the name (better, standard naming conventions), and querying the resulting table as needed for displaying the name with a space.

Ie this to modify the table:

strSQL = "ALTER TABLE YourTableName ADD ItemNumber AUTOINCREMENT(1, 1)"

and this to retrieve the data for display:

SELECT *, ItemNumber AS [Item Number]
FROM YourTable

again, just standard naming conventions.
I removed the quote marks from this line and it works fine.  Thanks.

strSQL = "ALTER TABLE YourTableName ADD "[Item Number]" AUTOINCREMENT(1, 1)"

new line"

strSQL = "ALTER TABLE YourTableName ADD [Item Number] AUTOINCREMENT(1, 1)"