A while back I wrote a post on using temp tables in your code and I mentioned using Alter table statements to modify your temp tables on the fly. Today I’m going to talk about adding a primary key using code.

Click for a free quote.

Primary Keys are good in Temp Tables
They can help up speed your queries and should be added when needed. To add a AutoNumber key that is also a primary key you will need to use two statments, the first creating the field and the second making it a primary key using the following syntax:

Alter Table TableName Add Column ColumnName AutoIncrement
Alter Table TableName Add Constraint ColumnName Primary Key(ColumnName)

Notice in the second statement Primary Key has a space between the words, and if you ever need a composite primary key just separate it by commas:

Alter Table TableName Add Constraint IndexName Primary Key(ColumnName1,ColumneName2,...)

 

Example
In the following example we use the table name tblTemp and the column name TempID as the primary key:

Dim strSQL as String
strSQL = "Alter Table tblTemp Add Column TempID AutoIncrement"
CurrentDb.Execute strSQL

strSQL = "Alter Table tblTemp Add Constraint TempID Primary Key(TempID)"
CurrentDb.Execute strSQL

Here we used the column name as the index name, making it easier to remember later what is the primary key name when you need to search on the specific index.

I encourage you to continue using temp tables in your code and bringing improved functionality to your Access applications.