简体   繁体   中英

Access SQL - ALTER COLUMN to AutoNumber?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM