Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access SQL - ALTER COLUMN to AutoNumber?

Tags:

sql

ms-access

How can you alter a table in MS Access using SQL to change a data type to AutoNumber?

I have tried to following with no success

ALTER TABLE PERSON ALTER COLUMN PERSON_ID Integer PRIMARY KEY counter
);
ALTER TABLE PERSON ALTER COLUMN PERSON_ID Integer PRIMARY KEY AUTONUMBER
);
ALTER TABLE PERSON ALTER COLUMN PERSON_ID Integer PRIMARY KEY AUTOINCREMENT
);

Each time I get the same issue "Syntax error" and it highlights the last word in the SQL.

like image 544
WillNZ Avatar asked Jun 16 '14 06:06

WillNZ


People also ask

How do you change a field to an automatic number in access?

On the Query menu, click Update Query. Double-click the new field from the referenced table to add it to the field list. In the Update To field, type [Main TableName]. [New AutoNumber field] to update the new field values in the referenced table.

How do I get AutoNumber to start from 100 in access?

For example, if you want the AutoNumber field to start at 100, enter 99 in the Number field. Create and run an append query to append the temporary table to the table whose AutoNumber value you want to change.

How does AutoNumber work in access?

AutoNumber is a type of data used in Microsoft Access tables to generate an automatically incremented numeric counter. It may be used to create an identity column which uniquely identifies each record of a table. Only one AutoNumber is allowed in each table. The data type was called Counter in Access 2.0.

Can an AutoNumber field be a primary key?

A table can have only one primary key. The values in the primary key fields must be unique. For this reason, many people use an AutoNumber field as their primary key. AutoNumber fields automatically add a new, unique number to each record in a table.


1 Answers

For a Data Definition (DDL) query in Access you use COUNTER to define an AutoNumber field. You were trying to use both Integer and counter on the same field, and that won't work.

I just tried this and it worked for me in Access 2010:

ALTER TABLE PERSON ALTER COLUMN PERSON_ID COUNTER PRIMARY KEY 

Note that in order for this statement to work

  • the table must be empty, and
  • the table must not already have a Primary Key, not even on the [PERSON_ID] field.

If the table already has rows in it then Access will not allow you to convert a Numeric (Long Integer) field to AutoNumber. In that case you need to create a new table with the AutoNumber Primary Key and then insert the rows from the old table into the new table.

For example, for an existing table named [PERSON] with columns

PERSON_ID INTEGER
PERSON_NAME TEXT(50)

you need to create a new table

CREATE TABLE PERSON_NEW (PERSON_ID COUNTER PRIMARY KEY, PERSON_NAME TEXT(50))

and then copy the records over

INSERT INTO PERSON_NEW
SELECT * FROM PERSON
like image 145
Gord Thompson Avatar answered Oct 12 '22 20:10

Gord Thompson