Many database applications use lookup tables. For example, you might have an Addresses table with records containing a State field. The values in this field must come from a the StateAbbrev field in the States lookup table. This program takes a table such as Addresses and generates a corresponding States table.
Enter the names of the database, original table and field (Addresses, State), the lookup table and field (State, StateAbbrev), and the relationship that should link the tables (leave this blank if you don't want to create a relationship).
When you click the Go button, the program opens the database. It then deletes any relation, index, and lookup table that it created in a previous run.
Next the code creates the new lookup table and adds the lookup field to it. It uses the same data type and size as the field in the original table (Addresses.State).
The lookup table's field should contain unique values (it wouldn't make sense to have two records with the value "CO" in the States table) so the program adds a unique index to the lookup field (States.StateAbbrev).
Now the program uses an INSERT INTO statement to copy the distinct values from the original field (Addresses.State) to the lookup field (States.StateAbbrev). Notice all of the [brackets]. These are only necessary if the names you pick are reserved words in Access. For example, if you name the table Table. This is a bad practice and it is better to avoid those keywords. If you are willing to do that, then remove all the brackets and the program will crash if you accidentally use an invalid name.
If you entered a relation name, the program then creates a many-to-one relation linking the two fields. This relation allows one lookup field value to correspond to many records in the original table. That makes sense because many Addresses records might share the same State value.
If you do not create this relationship, your code can still use the lookup table to make a list of the allowed states but the database will not enforce the integrity constraint for you.
|