Access tutorial.docx

download Access tutorial.docx

of 20

Transcript of Access tutorial.docx

  • 8/11/2019 Access tutorial.docx

    1/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Practical Database Modelling with

    MS Access 2007

    In this document well look at a problem description and create the data model based on that description.

    We will then create a relational database in MS Access 2007. We will create the tables, add attributes, add any

    necessary formatting and input masks, institute relationshipsbetween data entities, create formsfor practical

    front-end usage, and run some simple SQL queriesusing Access query builder.

    The theoretical aspects of data modelling are only dealt with briefly in this document: you should refer to your

    notes/recommended reading material for in-depth modelling theory & technique. This document is primarilydesigned to assist you with practical aspects of using MS Access for completing tasks relevant to your

    labs/assignment.

  • 8/11/2019 Access tutorial.docx

    2/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Problem Description

    Consider the following systems description.

    Ballybo hospital runs a number of clinics, e.g. clinics for Ear, Nose & Throat (ENT); Optometry; Dentistry etc.

    Each clinic has a number of nurses, each of whom work only at that clinic.

    Each clinic has several attending doctors, each of whom may work at several clinics.

    Each clinic also has patients. Patients are assumed to only attend one clinic at a time.

    Model this system with appropriate data entities, appropriate attributes of your choice, and relationships

    Build a database reflecting this data model using MS Access (or another RDBMS system of your choice)

    Build appropriate forms for administration staff to conveniently administrate this system

    Run sql queries (described later in this document)

  • 8/11/2019 Access tutorial.docx

    3/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Data Modelling

    (NB this is one perspective on modelling this data: you might have an equally valid alternative way of looking at this

    model. If so, feel free to ignore this part)

    Iteration 1:

    Start with the most obvious data entities about which we might want to collect information. Consider

    cardinalities between them.

    The system description states that nurses only work at one clinic. A clinic has a number of nurses working in it.

    The relationship between these entities is 1:m, denoted below in crows-foot notation. Similarly, the description

    states that each patient attends only one clinic at a time. A clinic presumably can have numerous patients.

    Again, this is a 1:m relationship. A doctor can work in several clinics, and clinics can have several doctors. This is

    a m:m relationship.

    Well model this data, and see if we spot any problems.

    One way of looking at First Normal Formis this: given an Entity Relationship Diagram (like that above), we have

    to get rid of all m:m relationships.

    We do this by creating a new table. We can name this new entity after the two tables in the m:m relationship.

    This new table will have a concatenated primary key, comprised of the primary keys of the two tables in the

    m:m relationship (it may have other attributes). We thus break the m:m relationship into two 1:m relationships:

    Iteration 2:

  • 8/11/2019 Access tutorial.docx

    4/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Before proceeding, we should check that the model conforms to 2NF and 3NF. For this simple example, well

    assume it does.

  • 8/11/2019 Access tutorial.docx

    5/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Database Design in MS Access 2007

    We now have the model or blueprint from which to implement the database in any relational DBMS system. In

    this document, well use MS Access 2007. Each data entity (Doctor, Clinic etc.) becomes a table in the database

    which we will create. We will use foreign keys to implement relationships between the entities.

    Create a Database:

    From the welcome screen in Access, select Blank Database. Name it and click Create

    Create Database Tables:

    When creating tables initially, dont worry about including Foreign Keys to link them to other tables. We will do

    that later. Simply build tables containing each entitys basic attributes.

    To create a new table at any time, (1)click Create in the top menu-bar, then (2)click Table in the ribbonmenu bar.

    Switch to Design Mode and add attributes, Primary Key

    By default, new tables open in Datasheet View. This view is used for reviewing/editing/adding data to the

    database.

    To make this table meaningful, we will give it a name, add attributes, and define a primary key. We do this by

    switching to Design View.

  • 8/11/2019 Access tutorial.docx

    6/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    To change views, click (1, below) Home, (2) View, and select (3) Design View. (when you switch views with a

    new table, you will be asked to name it. Go ahead and name it Nurses)

    Table Attributes and Field Properties

    Once in Design View, start to add attributes (1, below). Attributes are column headings for the table, and

    represent pieces of information we want to store about the entity. Some suitable attributes for nurses might be

    first name, last name, the shift they currently work, their phone number etc. The clinic they are attached to will

    also be an attribute, but we wontadd this just yet.... (the clinic attribute will be a foreign key used to link

    Nurses to Clinics, and its easier to sort out foreign keys later).Each attribute must have a data type: Text for

    textual information (name, address etc.), Number for numeric data (eg quantities) etc.

  • 8/11/2019 Access tutorial.docx

    7/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Field Properties

    We can also add things like input masks, and maximum field lengths to constrain what kinds of data the user can

    enter, and to format that data. In Field Properties (2), weve defined anInput maskfor a phone number of

    length 7 digits, with the first 3 digits being wrapped in brackets. When a user enters data, any formatting

    options, input masks etc. we have defined in Field Properties are enacted. For more help on any of the options

    in Field Properties, click into the text box associated with that option and press F1 for a list of options.

    We also must assign a primary key to each table (pks, along with fks, enable relationships between tables, and

    thus relational database management). By default, the first attribute in the table is set to be its primary key(denoted by a gold key icon in the blue box beside attribute name).

    Assign a suitable primary key to the nurses table (nurse_id). To make an attribute the primary key, highlight the

    attribute by clicking the blue box in the margin next to its name, then click Design in the top menu -bar, then

    Primary Key in the ribbon menu bar.

    Create tables for the following entities, and add their attributes in Design View. Implement any field properties

    you feel are necessary. Dont worry about creating the Doctor_Clinic table yet: well get to that soon.

    Entity Attributes

    Nurses nurse_id (pk)

    f_name

    l_name

    shift

    phone_no

    address

    Doctors f_name

    l_name

    phone_no

    grade

    Clinics clinic_name

    description

    ext_no

  • 8/11/2019 Access tutorial.docx

    8/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Patients f_name

    l_name

    phone_no

    insurance

    addr1

    addr_county

    nationality

    Creating relationships between tables using Lookup columns

    We now have most of the tables required for this data model, but we havent considered relationships between

    them yet.

    Relationships are built around the concept of foreign keys. A foreign key in a table is some attribute which we add

    to that table, which is also the primary key in another table. From our data model, we know that nurses are linked

    to clinics (and linked only tooneclinic). To create this relationship we take the primary key of the clinics table

    (clinic_id) and add it to the nurses table. One way to do this is to do this in MS Access is to use the Lookup Column

    feature.

    To the relationship between nurses and clinics, do the following:

    Select an empty row (the one under Address)

    Click Design in the top menu bar, then Lookup Column

    In the Lookup Wizard dialog that pops up, select I want the lookup column to look up the values in a table or

    query and click next

    We want to link Nurses to Clinics, so in the next page of the dialog select the Clinics tableand click Next

    In the next page of the wizard`, highlight Clinic ID (the primary key) in the left column, and clinic_name. Move

    these values to the right column using the adjacent arrow button. Click Next

    The final three screens of the wizard allow you to specify column formatting, sorting order (neither of these are

    important) and finally giving the field a name. Name the field clinic

  • 8/11/2019 Access tutorial.docx

    9/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    If all has gone well, you should have created a relationship between Nurses and Clinics. Furthermore, each time a

    user adds or edits a nurse in Datasheet view (or via a form), they will be able to select at which clinic they work at via

    a convenient drop-down menu.

    Well make sure the appropriate relationship has been created between Nurses and Clinics. To review relationships

    between tables at any time, do the following

    Click Database Tools in the top menu bar

    Click Relationships in the ribbon menu bar

    If the tables in question dont show up yet add them to the view: right-click the grey canvas area, select Show

    Table and add whatever tables you want to the view.

    Before creating any more relationships between tables, we should build the final table in the modelDoctor_Clinic

    [nb ** BUG ALERT ** Relationships view doesnt seem to update automatically. If you change any relationships and you dont

    seem to see any changes in Relationships view, try hiding the table in question and re-loading it. In Relationships view, just hide

    one/all tables which you have amended (highlight, press Delete), then load them back into the view (right-click -> show table)

    Add final table, concatenated primary key

    The entities/tables weve discussed so farare those we found when we performed our basic data modelling at the

    start of this document. Remember that we had to add another table (doctor_clinic) to fix a 1st

    Normal Form failure

    (to break up a m:m relationship between two entities). We will add this final table now.

  • 8/11/2019 Access tutorial.docx

    10/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    The primary difference between this table and the other tables weve created is that doctor_clinic must have a

    primary key made up of two attributes, in other words a concatenated primary key.

    This table will contain just 2 attributes: doctor and clinic. When entering data, both of these will be accessed via

    lookup columns.

    First, create a new table called doctor_clinic and enter design view (Create -> Table... View->Design View)

    Highlight the first row/attribute field by clicking the blue box adjacent to it

    Insert a lookup column here by clicking Design in the top menu bar, then Lookup Column in the ribbon menu.

    Set this lookup column to look up Doctor_ID (and l_name, if you like... just so whoever is entering data later

    knows the name of the doctor they are adding). Name this field Doctor and click Finish

    Create another lookup column to look up Clinic_ID (and name, if you like). Name this field clinic.

    The data type for both of these fields should be Number, as Doctor_id and Clinic_id both have datatype

    Number. (this should be done automatically by Access, but confirm)

    You should now have a design view looking like this:

    Now well turn these attributes into a concatenated primary key. This key will be comprised of both doctor and

    clinic. To create a concatenated primary key, do the following:

    Highlight the doctor attribute by clicking the blue box to the left of it.

    Hold down the Shift key.

    While keeping Shift pressed down, highlight the Clinic attribute by clicking the blue box next to it

    Keep shift held down! Right-click either doctor or clinic, and select Primary Key from the menu which pops

    up (right at the top of the menu)

    You should now see the primary key icon beside both doctor and clinic, as below:

  • 8/11/2019 Access tutorial.docx

    11/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    View relationships again (Database Tools in the top menu bar, Relationships in the Ribbon).

    If the new tables arent showing up yet, add them to the view. To add tables to the relationships view, right-click

    anywhere in the view (ie on the large grey panel on which the tables are drawn), and select Add Table from the

    resulting menu. Then select the tables you want to see (Doctors, Clinics, Doctor_Clinic).

    At this stage you should see something like this (if you have relationship lines crossing etc. make the model clearer

    by moving the tables around in this view):

  • 8/11/2019 Access tutorial.docx

    12/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Were only missing one table from this model: Patients. The Patients table should have a lookup column for Clinics

    (each patient attends one clinic). Create this column in Patients using methods outlined earlier. Then add the

    Patients table to the relationships view.

    Cardinality, Enforce Referential Integrity

    Finally, well add cardinality to each of these relationships and add referential integrity, to ensure that only valid data

    can be entered and to keep the database free of data inconsistencies.

    In the Relationships view, right-click any of the relationships (lines between tables). Select Edit Relationship

    from the popup menu (1 in the screenshot below).

    In the resulting dialog, select Enforce Referential Integrity (2)

    (3) shows the result after enforcing referential integrity between Nurses and Clinics: an overt 1:m relationship

    between the tables.

    Heres the final data model:

  • 8/11/2019 Access tutorial.docx

    13/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Forms

    We create forms to give end-users a convenient user experience for adding/editing data. Forms can be tied to a

    single table, or to several tables, or even to queries. They can be used to load other forms or to provide access toprecompiled queries and reports.

    Well first create a simple form for adding new nurses and editing existing nurse details. This form will allow us to

    navigate through nurse records, and add, delete, and edit nurse details.

    Open the Nurses table by double-clicking Nurses: Table in the left-most column of the window.(1)

    Then select Create (2) in the top menu, and Form in the ribbon menu. Enter Design View for this form by accessing the drop-down menu in Views (3) and selecting Design View

    Finally, access design tools for forms such as buttons etc. by clicking Design in the top menu.

    To review your work at any time and add data, click View (3) again.

  • 8/11/2019 Access tutorial.docx

    14/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Well first add navigation buttons to the form to help users navigate through records. Well add a button to go to the

    previous record by doing the following (make sure you have the Design ribbon menu activated, and are in Design

    View):

    Select Button in the Controls section of the Design ribbon menu (1)

    This gives you the option to draw your button anywhere in the design view canvas by clicking the location where

    you want the button to go, and dragging a short distance across the canvas (2)

    Having drawn the button, the Command Button Wizard appears (3)

    The command-button wizard gives you numerous options for what you want the button to do. Record Navigation

    deals with navigation options... e.g. accessing first/last record etc. The Record Operations category offers options to

    save records, delete records, and so on. Explore these categories and operations for yourself to see what kind of

    features you can add to your forms.

    Well add a simple navigation button in this example: a button for navigating to the previous Nurserecord in

    the database.

    In the command button wizard, select Record Navigation in the left column, then Go to previous record in the

    right-column, and click Next In the next page of the wizard, select whether you want the button to have a picture or text to describe its

    operation, and click next

    In the next screen, give the button a meaningful name (nurse_prevRecord)

    Click Finish. Click View in the ribbon menu bar to access the Form View (the actual, live version of the form)

    to check out its operation

    Having added one button to Navigate backwards through records, add another one to navigate forwards through

    records. (Click View in the ribbon to return to Design View)

    Now add these buttons:

    A forwards navigation button (In command button wizard, select Record Navigation then Go to next record)

  • 8/11/2019 Access tutorial.docx

    15/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    A button to go to a new, empty field to add a new nurse (in the wizard, Record Operations, then Add new

    record)

    A button to save any new records which you enter (Record Operation -> Save Record)

    A button to delete the present record (Record Operation -> Delete Record)

    Any other buttons you fancy, e.g. a print button

    When youre done, access the form by clicking View in the ribbon (also, dont forget to save the form). Enter/delete

    nurses and navigate through their records to your hearts content.

    Your form might look like this: note that any lookup columns, input masks etc. we specified when designing the

    tables are automatically implemented in forms.

    Patients should have a similar form. Go ahead and create it.

    More Complex Forms: Subforms

    Forms for Clinics and Doctors MIGHT be slightly different. Remember that doctors can work in multiple clinics, andthat clinics can have multiple doctors? We created a new table called Doctors_Clinics to get around what we called a

    First Normal Form failure.

    We COULD simply create simple forms, as described above, for Doctor, Clinic and Doctor_Clinic tables. But theres a

    problem with this, from the end-users point of view. Theres really no need for them to add clinics to doctors using a

    separate form: it would be much more convenient for them if they could add multiple clinics to each doctor, from

    within the doctor form. This may make more sense with an example.

    For each doctor, wed like to associate that doctor with potentially several clinics. To do this, well create a regular

    form for adding/editing doctors, and embed a subform derived from the Doctor_Clinic table.

  • 8/11/2019 Access tutorial.docx

    16/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    This process actually works best if we create the sub-form first: the one which we want to embed in the primary

    form. In this case, the sub-form will be built on Doctors_Clinics. So lets build a simple form for that table, the same

    way we built forms for nurses and patients.

    Open the Doctors_Clinics table in any view (double click Doctors_Clinics:Table in the left column of the

    window)

    Create a default form by clicking Create in the top menu, then Form in the ribbon

    Add a couple of command buttons to this form, for forwards and backwards navigation, and a Save button(View->Design View, then Design->Button etc.)

    Save the form, and close the form.

    Now lets build the basic Doctors form:you should know the process by now for creating a basic form (open the

    Doctors table, create->form). Add the usual buttons: navigation, save record, add new record, delete record.

    Ensure that you are in the design view for this form. Now well embed the subform, and tie it in to the primary form.

    Select Design, then Subform/Subreport (1 below). You should then draw out a space for the sub-form on the form canvas by clicking & dragging(2).

    When youve drawn the sub-form area, a wizard dialog appears (Subform Wizard). Select Use an existing Form

    and doctor_clinic (3) in the first page of this wizard.

    The second page of the wizard creates a link between the subform and the primary form. If your table

    relationships are correct, Access should be smart enough to know what kind of linkage we want here (we want

    to show every clinic for which this doctor is registered, and to add new clinics for this doctor). You should see

    the option Show doctor_clinic for every record in doctors using doctor_id. Thats exactly what we want. Select

    that.

    Click Finish

  • 8/11/2019 Access tutorial.docx

    17/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    The finished embedded form in Design view:

    Switching to Form view, you should now be able to add several clinics for every doctor. This will in turn create new

    records in the Doctors_Clinic table.

    One more thing...

    Before using these forms to add lots of doctors, nurses, clinics etc., you MIGHT want to edit each relationship (via

    Relationship view) to Cascade update related fields and Cascade Deleterelated fields.This will ensure that

    changes in one table cascade through the database to update related fields elsewhere.

  • 8/11/2019 Access tutorial.docx

    18/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    SQL, Query Design

    SQL runs behind the scenes of a RDBMS application to create, update, and query data. Access has a dedicated

    interface for creating SQL queries of variable complexity. You can use this interface, or simply write out SQL queries

    in longhand (practising the latter is worthwhile for exam preperation).

    To access the SQL query editor, click Create(1) in the ribbon, then Query Design (2).

    The query editor is best understood by creating examples.

    For our first query, well be using the Patients table. We have to load this table into the query canvas to use it. Right-

    click anywhere on the query canvas (3) and select Show Table, then select Patients.

    Using this view, queries are designed in the lower pane (4).

    Query 1 : how many patients does the hospital currently have?

    For this simple query, we only need the Patients table.

    Select Design in the top menu, then click the Totalsicon (1)(this adds a new Totals row in the lower pane ofthe queries interface, which gives you various additional query options)

  • 8/11/2019 Access tutorial.docx

    19/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    In Field in the lower pane, select patient_ID

    In Total, select Count (this counts the number of records for a given query)

    In the ribbon menu, click Run (2) to run the query. You should get the number of patients youve added to the

    database (via forms or via table view).

    Want to see the SQL which was generated by this process? Click the arrow underneath View in the ribbon

    menu and select SQL View.

    For the terminally lazy, here is the SQL which is generated by this process:

    SELECT Count(patients.patient_id) AS CountOfpatient_id

    FROM patients;

    Query 2: List those patients who attend Clinic [N]. Show their ID, l_name, and Insurance company

    Create a new query (Create->Query Design)

    Add the Patients table to the query canvas (right-click canvas, Show Table)

    Click (Design->Totals) to access further query options (1)

    Fill in the fields in the lower pane (2) as shown

    o Note the Where clause under Clinic. Clinics in the patients table are stored via primary key, which

    is a number.

    What this query says in (sorta) plain English: Show Patient_id, l_name and insurance for each patient where

    that patient attends whatever clinic has primary key=2

    Run the query by clicking Run

    Return to design view, or review the SQL syntax for this query in all its glory via the View button in the ribbon

    menu (beside Run)

  • 8/11/2019 Access tutorial.docx

    20/20

    V 1.0 John Conroy, Information Technology, NUI Galway, Oct. 2010

    Multi-table Queries

    Query 3: List all patients by the clinic name which they attend. Group by clinic ID.

    This is a multi-table query. Well show the clinic table as well as the patient table (right-click the grey canvas, show-

    table->clinics)

    Note that when we add another table to which Patients is linked, the relationshipbetween them is shown

    automatically.

    Enter the following parameters in the lower pane and click Run to view the results. Note that were sorting by ClinicID.