* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Table Design View - University of St Andrews
Microsoft Access wikipedia , lookup
Concurrency control wikipedia , lookup
Ingres (database) wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Functional Database Model wikipedia , lookup
Clusterpoint wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
University of St Andrews Library and Information Services Getting started with Microsoft Access An introduction to Relational Database Management Systems 2 Index Section 1: Introduction to Relational Database Design .......................................................................... 5 1.1 1.2 1.3 1.4 1.5 1.6 What is a database? ................................................................................................................... 5 The relational model ................................................................................................................... 5 Designing the database .............................................................................................................. 6 Data Normalisation ..................................................................................................................... 6 The Student/Module database ................................................................................................... 7 The Student/Module database Logical Design .......................................................................... 8 Section 2: Introduction to Microsoft Access ........................................................................................... 9 2.1 2.2 2.3 2.4 What is Microsoft Access? ......................................................................................................... 9 A note on versions ...................................................................................................................... 9 Using Microsoft Access at the University of St Andrews............................................................ 9 Starting up and creating a blank database ............................................................................... 10 Section 3: Table Creation ..................................................................................................................... 11 3.1 3.2 3.3 3.4 3.5 tblStudent Table in Design View .............................................................................................. 11 tblStudent Table Design Details ............................................................................................... 12 tblModule Table in Design View ............................................................................................... 13 tblModule Table Design Details ................................................................................................ 14 tblStudMod and tblSchoolDept Tables ..................................................................................... 15 Section 4: Form Creation...................................................................................................................... 16 4.1 4.2 4.3 4.3 4.4 Designing the Student Form ..................................................................................................... 16 Designing the Module Form ..................................................................................................... 19 frmModule Form Design View Properties................................................................................. 19 frmModule Form Design View Properties................................................................................. 20 The Dropdown Combo Box ...................................................................................................... 21 Section 5: Entering and Deleting Data ................................................................................................. 25 5.1 5.2 5.3 5.4 Adding and Editing Records ..................................................................................................... 25 Deleting records ....................................................................................................................... 25 tblStudent Table Data ............................................................................................................... 26 tblModule Table Data ............................................................................................................... 27 Section 6: Report Creation ................................................................................................................... 28 6.1 6.2 6.3 6.4 rptStudent Report in Design View ............................................................................................ 29 rptStudent Report Design View Properties............................................................................... 30 rptModule Report in Design View ............................................................................................. 31 rptModule Report Design View Properties ............................................................................... 32 Section 7: Querying the Database ....................................................................................................... 33 7.1 Opening the database .............................................................................................................. 33 7.2 Querying the database ............................................................................................................. 33 7.2.1 Querying the tblModule table ........................................................................................... 33 7.2.2 Saving your query ............................................................................................................ 35 7.3 More Criteria ............................................................................................................................. 35 7.4 Comparison operators .............................................................................................................. 36 7.5 More on the Modules report ..................................................................................................... 37 3 Section 8: Linking Tables and Setting Relationships ........................................................................... 38 8.1 8.2 Relating Tables ......................................................................................................................... 38 Referential Integrity .................................................................................................................. 39 Section 9: Manipulating Data Using Linked Tables .............................................................................. 41 9.1 9.2 9.3 9.4 9.5 9.7 8.9 The Finished Students & Modules Form .................................................................................. 41 The Main Student/Module Form ............................................................................................... 42 Properties for frmStudMod ....................................................................................................... 43 The Modules Subform .............................................................................................................. 44 frmSubStudMod ........................................................................................................................ 45 Linking the form and subform ................................................................................................... 46 Deleting records ....................................................................................................................... 50 Appendix 1: Data Types ....................................................................................................................... 51 Appendix 2: The Data Dictionary .......................................................................................................... 53 4 Section 1: Introduction to Relational Database Design Many scholars, software engineers and mathematicians have spent their lives devising the theories behind the relational model, and database design continues to evolve to suit the increasing complexity of data storage requirements. With limited time available it would be impossible to explain in any detail how a relational database is designed so, in this course, we can only hope to gain an insight into the basics of relational database design. But, by its conclusion, we hope you will have gained enough knowledge to design and construct simple databases which will adhere to the rules of the relational database model. 1.1 What is a database? Any information held on a computer can be described as a database, but the term is usually reserved for information that is structured in a way that makes it easy to store, retrieve and search. There are many database models, from the network data and hierarchical models to the relational model. Each of these models has been described in many learned treatises and would take too long to summarise. Microsoft Access is the most commonly used desktop relational database management system (RDBMS), and it is used widely in the University, so we will use Access to construct our database. 1.2 The relational model The aim of a relational database design (schema) is to remove data redundancy by storing repeating data in related tables. In this way we organise the data in a way that removes the duplication of data. If the schema is correctly designed we can combine data in related tables or queries when we need to use it, rather than having to store it repeatedly. This will greatly reduce the workload when entering data and, in turn, will reduce the human error which inevitably occurs when someone is required to enter or edit large amounts of data. Every spelling mistake or mistyped number is, potentially, a lost record when examining the statistical information available to the database user. Consider the case that you are required to store the progress of a group of students through one semester at the University of St Andrews. During that time they will study five modules and will take three examinations. For each module undertaken, there will be two separate marks awarded for coursework, and one mark will be recorded for each exam. This means that the student must have at least thirteen marks recorded to define his or her progress through the semester. In addition there is personal information about the student to record, such as name, age, sex, date of birth, home address, term-time address, telephone numbers, financial details, etc. In addition everything about the modules must be recorded - module number, title, level, etc. All of this data could easily amount to thousands of entries in a database. In a flat-file database each individual record must have ALL of the data pertinent to the record stored within it. In a relational database each individual record is composed of unique data and contains only references to repeating data. Imagine now that every time you add a new module to a student’s record, all the personal and module data must also be re-entered. This would be the case if the data were not structured in some way to remove the need to record everything each time a student’s progress was updated with new module or exam details. And what if the student changes his or her term-time address? Every record pertaining to that student would have to be retrospectively updated with the new information. If we use a database which conforms to the relational module we remove the need to re-enter everything in every record in the database. Some data is unique and some data repeats, some data changes regularly and some remains static. A student’s personal data is unique to him or her and a module’s data is unique to it, but a student will study a number of modules and each module will be studied by several students. In our case we must create a table to store the student data, another to store the module data and a third table to somehow match a particular student with all of the modules he or she studies. This third table could also store the marks for each exam and coursework undertaken. A fourth table will hold data about the school running each course. At this point in our sample database we will stop. At a 5 later time you may wish to consider adding tables to hold examination data, etc. but for now our database is complex enough. So, you can see that database design is of paramount importance. If you don’t get it right at the design stage you will find it impossible to store and retrieve the data at a later date. 1.3 Designing the database The easiest way of picturing the structure of a relational database is to see it as a number of related tables, each comprised of rows and columns. In database terminology the rows are known as records and the columns as fields. Each row will have a field, or combination of fields which will hold values that will be unique to that record. This field, or combination of fields, is called the primary key. By referring to the value(s) in the primary key we uniquely identify the data in the record to which it refers. By holding rows of similar data in tables we complete the database design. In a relational database management system such as Microsoft Access, data should not need to be repeated anywhere. Data are stored in tables and are related to other data by means of linking fields in corresponding tables. The goal of the database designer is to design a logical model (the schema) to represent this data. This process is called data normalisation. 1.4 Data Normalisation There are seven levels of normalisation: 1. un-normalised data All of the defined fields in an unorganised state 2. zeroth normal form The same fields placed in a single table 3. first normal form Remove repeating groups to new tables 4. second normal form Remove partial dependencies to new tables 5. third normal form Remove transitive dependencies to new tables 6. This is as far as most database design requires Boyce-Codd normal form 7. fourth normal form 8. fifth normal form As said previously it is not possible in this course to explain the technique behind the normalisation of data; it would take too long, but using common sense and asking the question: ‘Which data belongs together?’ should suffice to get a reasonable approximation of data normalised to third normal form. After some practice it becomes natural to ‘see’ which data is unique and which repeats. An obvious example in our database is that of student data and module data. Let us look first at the student data. In themselves, the student’s name, age, sex, address, etc. have no relevance to a module so they obviously ‘belong’ with the student table. Similarly, the module title, level, etc. have no relevance to the student data and therefore ‘belong’ with the module table. If ten student records are entered in the database each record will be unique, but each of the ten students will study the same modules so the module data will repeat ten times for each module entered. The opposite also occurs. If the students each study five modules there must be five repeated records for each student as well. So now we have fifty records in an un-normalised table containing both student and module data. In this case the student data and the module data need to be held in separate tables. 6 A simple rule of thumb is to ask the question: Can a record in one table be related to more than one record in another table? If the answer is yes, this is a called a one-to-many relationship (1:M). In this case a relationship can be established between the two tables. If the answer to the question is no, then we have a one-to-one relationship (1:1) and if this is the case the data belongs in the same table. There is, however, a third possible answer. For example; a student can study MANY modules and a module will be studied by MANY students. Here we have a many-to-many relationship (M:N) between students and modules. Relational databases do not like many-to-many relationships so we must resolve this problem by creating a third table. This table will have two fields; the primary keys from the two tables in question. By selecting both the fields and designating them as a shared (concatenated) primary key we can allow repeated entries for a module and repeated entries for a student but we prohibit the same combination of student and module appearing in the same row (record) more than once. The standard way of allowing relationships to be set is to place a copy of the primary key from the ONE side into the MANY side table at the database design stage. This field becomes the foreign key when inserted into the many-side table. Every time a repeating value is entered into the ‘many’ table the primary key value from the ‘one’ side is also recorded in the record. Thus the two tables can be directly related on this field. We will see this theory put into practice when we design the Student/Module database which we will create and use in this course. As stated earlier there are seven levels of normalisation, but most database designers stop at third normal form. The rules of normalisation are defined using set algebra and to explain them in any detail would take far too long. This may be the subject of a more advanced database design course in the future However a less experienced user can approximate organising their data to third normal form by answering a number of predefined questions of the data … and, of course, lots of practice! 1.5 The Student/Module database The database we will create will store minimal data about students, modules, and schools. Of course, if the database were to be used in ‘real life’ situation, we would be required to hold more data and create more tables but, for the purposes of the course, the tables we define will suffice. It seems logical that we would store student data in one table and module data in another, but we must test this assumption. If we ask the question ‘Can a record in a table holding student data be related to more than one module?’ the answer is yes, a student studies many modules. In this case we must split the module data out to another table. So, at this time we need to create two tables, one to hold student data and one to hold module data. The student table should be on the ONE side of the relationship and the module table on the MANY side. So, according to the rules of the relational model, when we construct the module table there must be a field in the module table to hold the student ID. However, this would break the rules as well. The relationship between students and modules is a many-to-many relationship, which is not allowed in relational database design. A student studies MANY modules and a module is studied by MANY students. To overcome this problem we must create a third table to hold the primary keys from the student and module tables. This removes the M:N relationship and replaces it with two 1:M relationships, a state which the relational model requires. You will see this graphically if you study the diagram on page 34 of this workbook. Let us now consider the school data. Once more we ask the question ‘‘can a record in the module table be related to more than one record in the school/dept table?’ In our database a module is only taught by one school, but a school teaches many modules, so school data has a 1:M relationship with the module table. In this case we must create a fourth table to hold the school data. 7 So the final database will consist of four tables: The student table (tblStudent) This table will hold data unique to the student, e.g. student ID, name, address, year of birth, etc. The module table (tblModule) This table will hold data unique to the module, e.g. module number, name, year, etc. The school/dept table (tblSchoolDept) This table will hold data unique to the school running the module, e.g. school number and name The student/module matching table (tblStudMod) This table will hold two pieces of data: the module number and the student ID, and will be used to match students and the modules they study. 1.6 The Student/Module database Logical Design Student table (tblStudent) student_id 030003759 030005909 surname Willson Friedrik forenames Malcolm Hermann year_of_birth 1983 1980 The link between tblStudent and tblStudMod is set on the student_id Student/Module table (tblStudMod) student_id module_id 030003759 030005909 BL3003 BL3003 module_id BL3003 The link between tblStudMod and tblModule is set on the module_id title Membranes & Cell Communication school_dept_id 1 year 2004-05 Module table (tblModule) The link between tblModule and tblSchoolDept is set on the school_dept_id School/Dept table (tblSchoolDept) school_dept_id school_dept 1 2 Biology Physics & Astronomy 8 Section 2: Introduction to Microsoft Access 2.1 What is Microsoft Access? Microsoft Access is a Relational Database Management System (RDBMS) which enables us to 2.2 create tables and enter data into them specify relationships between the tables interrogate the data create forms providing easy views of the data create report layouts to print out selected parts of the data in understandable and presentable formats create free-standing applications with their own customised interface so that the “end-users” do not need to learn how to use Access A note on versions These notes refer to MS Access 2003. Many users at the University still have MS Access 97 but versions of Access prior to version 2000 are not compatible with the networking system in the PC classrooms. However the differences between the versions are slight, and Access 2000/2003 can open and use databases created with earlier versions, and can usually save a database in a format which the earlier version can handle. 2.3 Using Microsoft Access at the University of St Andrews. For those users wishing to use existing data, e.g. from the University’s Data Warehouse, you can use Microsoft Access to build a database application using the data available to you. Tables need not be held within the database itself, but can be ‘attached’ from an external source. You can also use properly formatted Microsoft Excel spreadsheets or text files as your data sources. For those of you wishing to create databases with new data there is a section on table creation and data entry Whatever your needs we hope that you will gain a basic knowledge of how to create, maintain and customise simple MS Access databases. 9 2.4 Starting up and creating a blank database Choose Programs from the Start menu and then choose Microsoft Office, and then Microsoft Access In the initial dialog-box select the Blank Database option and click OK The first thing you are asked to do is file the new database – that is, save it on disk: complete the dialog-box as usual, saving the database as studmod.mdb in the Save In: box select your floppy disk (the A: drive) or your “home directory” (the H drive) in the File Name: box type a name: studmod click Create The Database Window 10 Section 3: Table Creation When you select a Data Type you will notice that the properties for the field may change. This is because some field types have settings which cannot be defined by the database designer, e.g. a Memo field will always by 64KB in size, so the Field Size property of a Memo field is not present, However a Text field can be any size between 1 byte and 255 bytes so, when you define a field as a Text field, you are able to define its size. For the purposes of creating this sample database defining the field sizes, etc. is not so important but, if you were designing a database to hold many hundreds of thousands of records, you would create a much more efficient data structure if field sizes were constrained so that disk space and memory requirements were not wasted when storing or remembering empty space. 3.1 tblStudent Table in Design View Data type Data Properties First we will create the Student table. Make sure you are able to see the database window then click the Tables option, select New and then Design View. The table design dialog box will open, similar to the illustration above. On the next page is a list of the fields and their attributes. Create the fields then save the table as tblStudent. The prefix tbl denotes that this particular object in the database is a table. To define the primary key, select the student_Id row by placing your mouse pointer in the grey box immediately to the left of the Field Name and left-click. This will highlight the student_id row. Now go up to the toolbar and click the key. key. This will mark student_id as the table’s primary 11 3.2 tblStudent Table Design Details Complete the tblStudent table by creating the following fields in the design window. Set the properties of the fields as follows: Field Name Properties Data Type Field Size Caption Indexed? student_id Text 50 Student ID surname Text 30 forenames Text Number year_of_birth Required Primary Key Yes (No Duplicates)* Yes Yes Surname No Yes No 30 Forename(s) No No No Integer Year of Birth Yes No No * This will be set automatically when you define the field as the primary key For a brief description of data types see Appendix 1 12 Default Value 3.3 tblModule Table in Design View Now we will create the Module table. Make sure you are able to see the database window then click the Tables option, select New and then Design View. The table design dialog box will open similar to the illustration below. tblModule Table Design View On the next page is a list of the fields and their attributes. Create the fields then save the table as tblModule. 13 3.4 tblModule Table Design Details Complete the tblModule table by creating the following fields in the design window. Set the properties of the fields as follows: Field Name Properties Data Type Field Size Caption Indexed? module_id Text 30 Module No. module_name Text 100 school_dept_id Number acad_year under_post Required Primary Key Yes (No Duplicates) * Yes Yes Module Name No Yes No Long Integer School/Dept. Yes No No Text 30 Academic Year No 2004-05 No No Number Byte Undergrad/Postgrad Yes 1 No No * This will be set automatically when you define the field as the primary key For a brief description of data types see Appendix 1 14 Default Value 3.5 tblStudMod and tblSchoolDept Tables To complete the database structure we will now create the other two tables in the database. One of the tables, tblStudMod, is required to remove a many to many relationship between tblStudent and tblModule (relationship types are explained later in the workbook). The other table, tblSchoolDept will hold details about the school a module is associated with. The first thing to do is create our third table. Create the following table and save it as tblStudMod Field Name Data Type student_id Text module_id Text Field Size Caption Indexed 50 Student ID 50 Module No. Default Value Required Primary Key Yes (Duplicates OK) Yes Yes Yes (Duplicates OK) Yes Yes Now that we have created this third table you will see that students can be matched with modules by entering the corresponding ID numbers. Student IDs can repeat, as can Module numbers, but the same combination of student_id /module_id is prohibited in a record by the combined primary key. In a later section we will use this table to match students with modules on a form and report. There is no need to create a data entry form for this table as the data will be added automatically when a student is matched with the modules he or she is studying. Finally, create the School/Department table and save it as tblSchoolDept Field Name Data Type Field Size Caption Indexed Default Value Required Primary Key school_dept_id Auto number Long Integer School/Dept ID Yes (No Duplicates) Yes Yes school_dept Text 50 School/Dept No Yes No This table will be used later to display the numeric data held in the school_dept field in the table, tblModule as a text value. If you feel like doing some extra work create a form to allow a user to enter data into this table. If you don’t wish to do this at the moment you can enter the following data straight into the table. Make sure the Database Window is visible and that Tables is selected. Double-click tblSchoolDept to open the table for data entry and enter the following data. You do not need to enter the ID number as this field will automatically generate a sequential number. school_dept_id school_dept 1 Biology 2 Physics & Astronomy 3 Modern Languages 4 International Relations 5 Psychology 15 Section 4: Form Creation Forms allow you to create a simple user interface for the inputting and editing of data in the database. In this exercise we will create two forms, one each for inputting data to the tblStudent and tblModule tables. 4.1 Designing the Student Form Make sure you are able to see the database window then click the Forms option, select New. A new dialog box will open. Select Design View and in the section marked - Choose the table or query where the object’s data comes from: - use the drop-down list to select the tblStudent table. Click OK to complete this part of the process. A blank form will now appear in design mode. If the form Properties and Field List windows are not visible select the View menu and click on these two options to make them visible. Move your cursor to the edge of the form background (the bit with the grid). Your cursor should change to a cross-shape. Click, hold the mouse button, and drag the form background to make it a little larger. Now highlight the first field in the Field List dialog box, hold the left shift key down and click on the last field in the list. All fields should now be highlighted. Drag the block of fields and drop them somewhere in the middle of the form background. You will see that the fields now appear as controls on the form, each with its caption denoting its function. Drag each control into its correct position by clicking and holding the left mouse button (the cursor will change to a small hand shape). 16 Now it’s time to set the form’s Properties. Every object on the form has properties so; to ensure that you are setting the form’s properties, check that it says ‘form’ in the Drop-down list. If this is not the case select ‘form’ from the drop-down list at the top of the Properties window. Amend the properties as in the illustration below: Drop-down list box Ensure the tblStudent table is selected This will display as the form’s title. Set to Single Form to show only one complete record at a time. When the form is a Single Form there is no need to display vertical and horizontal scroll bars When the form is a Single Form there is rarely a need to display Record Selectors (the strip down the left side of the form when showing multiple records Set this to No to prevent the form from maximising to fill the screen Set this to Yes to make the form appear in the centre of the screen When you have completed these property settings resize the form’s background neatly round the controls and view the form by selecting Form View from the View Menu. You will probably need to resize the form again in this new view. 17 When you have resized the form save it as frmStudent. The prefix frm denotes that this particular object in the database is a form. Because you have set the form’s Auto Resize property to No and Auto Centre to Yes the form will retain its size and will open up in the centre of the screen. The Student form in Design view The Student form in Form view 18 4.2 Designing the Module Form Repeating the previous processes we will now create the modules form. Remember to name it frmModule in keeping with our naming convention. You will note that there are a couple of new controls on this form: a drop down combo box and an option group. Please read on for an explanation of how to create these controls. The Module form in Form view Create this control using the Combo box wizard (see page 20) This is an Option Group. Create this object group by clicking on the button on the Toolbox and then follow the steps in the Option Group Wizard. The Module form in Design view 19 4.3 frmModule Form Design View Properties Ensure the module table is selected This will display as the form’s title. Set to Single Form to show only one complete record at a time. When the form is a Single Form there is no need to display vertical and horizontal scroll bars When the form is a Single Form there is no need to display Record Selectors (the strip down the left side of the form when showing multiple records) Set this to No to prevent the form from maximising to fill the screen Set this to Yes to make the form appear in the centre of the screen 20 4.4 The Dropdown Combo Box We will select the school_dept_id to be stored within a module’s details by selecting the school or department from a dropdown list. We will use a wizard to create this control: If the Toolbox menu is not visible make it so by selecting Toolbox from the View menu. Select the dropdown combo box tool and click on the form in the general area you wish to place this control. A wizard will start which will lead you through the steps in building the dropdown list. Dropdown combo box tool Select this option Click Next > to continue 21 We will take the values from the tblSchoolDept table Click Next > to continue Highlight the required field in the left-side list and move them to the right by clicking here. Click Next > to continue 22 Select the school_dept field to sort the data alphabetically in ascending order N.B. This wizard screen is not available in MS Access 2000. It only appears when using Access 2003 Click Next > to continue Select this option to hide the ID field Click Next > to continue 23 Select module_id as the field to store the value in Click Next > to continue Enter anything here as we will delete the label in the final form later, and then click Finish. When you have successfully completed the dropdown list delete its caption and position it correctly on the form. Now set the form’s properties: 24 Section 5: Entering and Deleting Data 5.1 Adding and Editing Records The navigation buttons appear at the bottom of every form and subform. Use the buttons to select or add a record. FIRST record PREVIOUS record NEXT record LAST record NEW record The next step is to enter data into the two forms you have just created. To select a form make sure you are able to see the Database Window then click the Forms option and double-click the required form. The form will open as in the illustration on page 12. Use the mouse, tab key or enter key to move from field to field. You will not be able to enter data in the ID field as it is an automatically generated number which will increment when a new record is entered. 5.2 Deleting records Place the cursor in a field of the record you wish to delete then click the delete button as illustrated below or go to the Edit menu and select Delete Record. Click this button to delete a record On the following pages are some sample data. Enter this data into the database using the appropriate forms. 25 5.3 tblStudent Table Data student_id surname forenames year_of_birth 030003759 Willson Malcolm 1983 030005276 Petrovic Vaclav 1980 030005909 Friedrik Hermann 1980 030005923 Petrie Gordon 1969 040002559 Jones Robert 1985 040003572 Phillips Peter 1978 040004409 Green Gilbert 1975 040005059 Morrison James 1986 040008649 Simpson Maggie 1982 040011192 Wallace Walter 1980 26 5.4 tblModule Table Data module_id module_name school_dept acad_year under_post AS1001 Astronomy and Astrophysics 1 2 2004-05 1 BL1001 Cell Biology & Genetics 1 2004-05 1 BL3003 Membranes & Cell Communication 1 2004-05 1 ID5001 Enterprise, Creativity & Innovation 1 2004-05 2 IR1005 Themes in Twentieth-century International Relations 4 2004-05 1 IR3022 International Relations and International Law 4 2004-05 1 IT1001 Introduction to Italian Language 3 2004-05 1 IT1003 Italian Language Intermediate I 3 2004-05 1 IT1005 Contemporary Italian Short Story 3 2004-05 1 PH1011 Physics 1A 2 2004-05 1 PS1001 Psychology I 5 2004-05 1 PS1002 Psychology II 5 2004-05 1 PS1901 Psychology in Everyday Life 1 5 2004-05 1 SP1011 Spanish for Science Students I 3 2004-05 1 SP1012 Spanish for Science Students II 3 2004-05 1 27 Section 6: Report Creation Creating reports is similar to creating forms. Make sure you are able to see the Database Window then click the Reports option, select New. A new dialog box will open. Select Design View and in the section marked - Choose the table or query where the object’s data comes from: - use the dropdown list to select the tblStudent table. Click OK to complete this part of the process. A blank report will now appear in design mode. If the report Properties and Field List windows are not visible select the View menu and click on these two options to make them visible. Move your cursor to the edge of the report background (the bit with the grid). Your cursor should change to a cross-shape. Click, hold and drag the edge of the report background to make it a little larger. Now highlight the first field in the Field List dialog box, hold the left shift key down and click on the last field in the list. All fields should now be highlighted. Drag the block of fields and drop them on the report background. You will see that the fields now appear as controls on the report, each with its caption denoting its function. Drag each control into its correct position by clicking and holding the left mouse button (the cursor will change to a small hand shape). The control’s caption will move with the control. For the student report we wish the captions to be ‘decoupled’ from their controls as we do not want the captions to be repeated in every row of the data. If a control is highlighted (it has adjustment handles around it) click on the report background to deselect it then click the control’s caption only. Use Ctrl+X to cut the caption, click on the page header section and use Ctrl+V to paste it. Now move it into position as a column heading. Experiment with various layouts until you are happy. 28 6.1 rptStudent Report in Design View Place the text box captions in the Page Header section by using Ctrl+X to cut the captions, clicking on the page header section and using Ctrl+V to paste them. Then move them into position as column headings. Place and size the text boxes in the detail section to allow all the data to be displayed. Periodically view the report in Report view to check the spacing/sizing 29 6.2 rptStudent Report Design View Properties Ensure the tblStudent table is selected All other properties can be left at their default settings The students report in Report view When you have completed the design of the report save it as rptStudent. The prefix rpt denotes that this particular object in the database is a report. The next step is to preview the report you have just created. To select the report make sure you are able to see the database window then click the Reports option and double-click the rptStudent report. The report will open displaying all records in the tblStudent table. Now repeat the process for the Modules report, saving it as rptModule 30 6.3 rptModule Report in Design View The only significant difference between the student and the module reports is that the student report has a table as its data source. Ultimately the module report will be populated using a query. We will use a query to populate it as we need to add a calculated field – status. The status field will display whether a module is taught at undergraduate or postgraduate level. The status field does not exist in the database. The values displayed will be created ‘on the fly’ when the report is viewed or printed. The values displayed in this text box are derived from the data held in the under_post field in the tblModule table. The under_post field has a value of 1 or 2, with 1 representing Undergraduate, and 2 representing Postgraduate. These values are meaningless to the uninformed observer so we will force the report to display the words Undergraduate or Postgraduate, depending on the value in the underlying record. We will learn about queries next so, for the time being, use the tblModule table as the data source for this report. 31 6.4 rptModule Report Design View Properties Ensure the tblModule table is selected All other properties can be left at their default settings 5 The modules report in Report view The final step is to preview the report you have just created. To select the report make sure you are able to see the database window then click the Reports option and double-click the rptModule report. The report will open displaying all records in the tblModule table. At the moment the Under/Post Graduate column will display numbers. When you have gained some more experience using queries you can return to this report to replace its table data source with a query using a function to display textual data instead (see Page 28). 32 Section 7: Querying the Database In this section we shall work with the database that has the two tables that have already been created and populated with data. 7.1 Opening the database If Access is not already running, start it up as usual. If it is running, close all the open windows Choose Open Database from the File menu and use the dialog-box to locate and open the database studmod.mdb In the database window click on the Tables tab: you will see you have tables called tblModule and tblStudent. Look at the tblModule and tblStudent tables In the Tables tab, double-click on tblModule This will launch the tblModule table: scroll up and down to look through the records in the tblModule table Open the tblStudent table and scroll through to see the list of students 7.2 Querying the database We shall start with a simple single-table query, then see how the tables can be linked to create more complex queries. 7.2.1 Querying the tblModule table Click the Queries tab in the database window Click New Choose Design View and click OK Two windows will be displayed, the query-design window called Query1 and Show Table windows: in the Show Table window click the Tables tab Select tblModule from the list of tables and click Add We are only using one table for this query, so click Close to close the Show Table window The query design window consists of two parts: the upper part shows which tables are involved in the query (the tables window); in the lower part you can select which fields from the table(s) are to be used (the query grid). You can use the fields in several different ways in constructing your query: you must choose at least one field to be displayed in the answer you can specify values to search for in particular fields: these are known as the query criteria you can use fields as the basis for sorting the answer 33 We shall run a query to list the module names and numbers for all the modules, listed in number order, starting with first year modules. Complete the first column in the lower part of the window as shown below Your first column should now look like this 1 Click on the down arrow in the Field box and choose module_name from the list of fields 2 Access will automatically fill in the name of the table 3 Leave the Sort box blank as we shall not sort on the title 4 Access will put a tick in the Show box: leave it there as we want to display the module titles 5 Leave the Criteria box blank: we want to display all the records. You fill in the Criteria box if you want to select certain records and leave out others Now select options for the second column click in the top row of the second column of the query grid click on the down arrow and choose module_id from the list of fields in the third row choose Ascending to sort the records in alphabetical order starting with A your second column should now look like this To run the query choose Run from the Query menu The results of the query will be displayed in datasheet format, as shown next. 34 The first column is too narrow and the second is too wide for the data they contain. You can correct the widths by pointing and double-clicking Point here at the line between the column labels. When the pointer becomes a doubleheaded arrow, double-click Go back to Query Design view by choosing Design View from the View menu or clicking the button Add a query criterion in the module_id column of the query design window Click the button to run the query The result of your query should look similar to this: 7.2.2 7.3 Saving your query Choose Save from the File menu In the dialog-box type a name that describes the query, for instance qryModules_P and click OK (the prefix qry denotes a query). Close the query More Criteria We will now try another select query, using a different criterion. Create a new query, just like the one you have just finished, but this time use the tblStudent table. This time use the student_id, surname and year_of_birth fields in the query. Enter them into the query grid as usual then run the query. 35 Now enter >1968 AND <1982 in the Criteria grid of the year_of_birth field. This will limit the records returned to those students whose year of birth is between 1969 and 1981. Note the use of the Boolean operator AND. This ensures that both parts of the criterion are true. Try substituting AND with OR. See what records are returned now. Can you explain why this happens? 7.4 Comparison operators The greater than and less than signs (> and <) are known as comparison operators and it’s important to be clear what they mean. Which of the following years are included by the criterion used here, >1980 AND <1985: 1980? 1981? 1984? 1985? The other comparison operators are >= greater than or equal to <= less than or equal = equal to <> not equal to Like similar to To save your query: Choose Save from the File menu In the dialog-box type a name that describes the query, for instance qryStudent_DOB and click OK Close the query The query will now be listed in the database window. You might wonder why the Save As dialog-box is not like other Save As dialog-boxes in Windows applications. The reason is that you are not saving the query as a file. Your queries, as well as tables, forms and everything, are all stored within the one database file. 36 What you have saved is the query not the answer. If you add new records for films from the 1950s, and then run the query again, you will get a different answer, including the newly added (or changed) records. 7.5 More on the Modules report Now that you know your way around the query grid we will update the Modules report to replace the numerical data displayed in the Under/Post Graduate column with textual data. Make sure the database window is visible and that Queries is selected. Create a new query and create the following query: Add the two tables tblModule and tblSchoolDept. You will notice that the relationship between school_dept_id in tblModule and school_dept_id in tblSchoolDept is established automatically. This is because the field names are the same. At this time it is not necessary to set referential integrity. In the query grid enter the module_id, module_name and acad_year fields from tblModule and the school_dept field from tblSchoolDept. This will display the selected data from the Modules table but will show the school rather than is numerical equivalent. To complete the query we will create a ‘virtual’ field called status to display the module level. Select the first blank column in the grid and in the Field: row type the following: status:IIF([under_post]=1,”Undergraduate”,”Postgraduate”) This will replace the value displayed in the under_post field with the word Undergraduate or Postgraduate, depending on its underlying value Make sure there is a tick in the Show: check-box and run the query. If all looks correct save the query as qryRptModules. Finally return to the report, rptModule, and open it in design view. In the report properties change the record source from tblModule to qryRptModules. Run the report. You will see that the Under/Post Graduate column will now show more understandable data. 37 Section 8: Linking Tables and Setting Relationships At the moment we have four tables, two forms and two reports. We can input, edit and view data about students and modules. However we have no means of linking specific students with specific modules, or for viewing reports with all of this data shown. What we need to do now is to link the tables together by setting relationships between them. 8.1 Relating Tables To set relationships for the tables in the database go to the Tools menu and select Relationships... Add the four tables by clicking the button. toolbar button. Highlight the tables and click the Add If the relationships are not added automatically create them as follows: Locate the student_id field in the tblStudent table. Click on this field and drag it over the student_id field in the tblStudMod table. A dialog box will open which allows you to set join parameters. We will accept the default settings for now so click OK. Locate the module_id field in the tblModule table. Click on this field and drag it over the module_id field in the tblStudMod table. A dialog box will open which allows you to set join parameters. We will accept the default settings for now so click OK. Locate the school_dept_id field in the tblSchoolDept table. Click on this field and drag it over the school_dept field in the tblModule table. A dialog box will open which allows you to set join parameters. We will accept the default settings for now so click OK. It is not strictly necessary to create relationships here as relationships can be set in individual queries. However, if you set relationships in the Relationships window these will be created for you automatically when you build a query using linked tables. The Relationships window with the completed database is shown on the next page. 38 The Relationships window with all relationships set 8.2 Referential Integrity Key fields There are several reasons for defining fields as key-fields, one of which is that it enables Access to establish “referential integrity” between linked tables. This means, roughly speaking, that Access can ensure that you don’t enter inconsistent data in your linked tables. For example, it will prevent you from referring to a student in the tblStudMod table if a related student record does not occur already in the tblStudent table. Close the Relationships window by clicking on the cross in its top right corner In the Database window click the Tables tab Click on the tblStudent table Click Design to go to Table Design View Notice the little key icon beside the student_id field, indicating that it is the primary key The way to make a field a primary key is to select the field by clicking, and then click the Key button on the toolbar. Clicking this button again will cancel the key. Don’t do this now, as we want to leave the student_id field as the primary key. Close the tblStudent table Open the tblModule table in Table Design View Note that the module_id is marked as a primary key and then close the table Open the tblStudMod table in Table Design View Note that both fields in this table are marked with the key symbol, meaning that both fields together constitute the primary key. The student_id and module_id fields together constitute the primary key, which means that: 39 a student ID can appear more than once in the table a module number can appear more than once in the table any particular pairing of a student ID with a module number can only appear once Enforcing referential integrity in the Relationships window Having seen what is meant by a key field, we’ll go back to the Relationships window to learn more about the relationships between our three tables Choose Relationships from the Tools menu Point at the line running from tblStudMod to tblStudent and click. If you have clicked in the right place the line will become thicker, indicating that you have selected the relationship. It is quite hard to click in exactly the right place, so you may have to try several times before successfully selecting the relationship. Choose Edit Relationship from the Relationships menu This command will not be available unless you have succeeded in selecting a relationship. The dialog-box shows you which fields are involved in the relationship, and that the relationship is “one-to-many” (both of which we knew already), and also what sort of referential integrity is in force. The significant point for our database is that the Cascade Delete Related Records option is turned ON. Now, if you delete a student from the tblStudent table, all records in the related table (tblStudMod) which refer to the deleted student will also be deleted. This maintains referential integrity by ensuring that there are no students referred to in tblStudMod who are not already in the tblStudent table We don’t want to make any changes at present, so click Cancel Now click on the link between tblStudMod and tblModule and choose Edit Relationship from the Relationships menu Check that the relationship is defined in just the same way as for the tblStudent / tblStudMod relationship and then click Cancel Close the Relationships window 40 Section 9: Manipulating Data Using Linked Tables In this section we will create a form to allow the data entry of students and the modules which they study. This form will consist of a main form to show details about a single student and a linked subform to show details about the modules the student is studying. 9.1 The Finished Students & Modules Form Head section: Student details Detail section: Module details The modules subform will be superimposed on the student form and both will be linked on the student_id. In this way, when a student is selected on the main form the subform will automatically move to the corresponding record(s) in the tblStudMod table. Note that the upper section of the form contains data about the student and the lower sections shows repeating data about the modules the student is studying. In order to create this view of the data we need to create two forms; the main student form and the modules subform. The student form will be populated by the tblStudent table but the subform needs to use a query based on three tables – tblModule, tblStudMod and tblSchoolDept. 41 9.2 The Main Student/Module Form The Students/Modules form is created in a similar way to the frmStudent form you created earlier in the course. The main difference is that all the student controls on the form are placed in the Form Header section, not the Detail section. The details section will be the section where we place the modules subform, so extend the details section in preparation for this. When you have completed the form save it as frmStudMod. Drag the controls onto the form and arrange them to suit. When you are happy enter the properties for the form as instructed below. frmStudMod in design view 42 9.3 Properties for frmStudMod Ensure the tblStudent table is selected This will display as the form’s title. Set to Single Form to show only one complete record at a time. When the form is a Single Form there is no need to display vertical and horizontal scroll bars When the form is a Single Form there is no need to display Record Selectors (the strip down the left side of the form when showing multiple records) Set this to No to prevent the form from maximising to fill the screen Set this to Yes to make the form appear in the centre of the screen 43 9.4 The Modules Subform As stated earlier this form differs slightly, in that it uses a query to populate the form. This query uses three linked tables, the tblModule, tblStudMod and tblSchoolDept. The Query Start a new query and add the three tables, tblModule, tblStudMod and tblSchoolDept. Drag the student_id and module_id fields from the tblStudMod table into the design grid Drag acad_year from the tblModule table into the grid (We don’t need the module_id as it is already represented from the tblStudMod table) The link between the two tables on module_id should be set automatically but if not, click and hold the module_id in the tblModule table and drop it on the module_id in the tblStudMod table. Drag the school_dept field from the tblSchoolDept table into the design grid. Save the query as qryFrmStudMod. The prefix qry denotes that this object in the database is a query and the name suggests that the query is used in the frmStudMod form. qryFrmStudMod in design view 44 9.5 frmSubStudMod This form is created in a similar way to the frmStudent form you created earlier in the course. There are a number of differences however: The Record Source for the form is our newly-created query qryFrmStudMod The labels are placed in the Form Header section, not the Detail section. The details section is the section where we place the controls which display the module data. This way the data can repeat but the labels become column headings. The form will be set to display continuous data, i.e. it will display multiple records simultaneously if they exist. The module_id text box will be replaced by a dropdown combo box to select the module_id 45 Ensure qryFrmSubStudMod is selected Set to Continuous Forms to show multiple records Show vertical scrollbars only Shows record selectors Accept the default settings for all other properties When you are happy that you have completed the form save it as frmSubStudMod. The name suggests that this is a subform on the form frmStudMod. 9.7 Linking the form and subform Open frmStudMod in Design View, ensure that it is displayed in a window and move the window on the screen so that you can also see the Database Window. 46 47 Select the form frmSubMovAct and drag it onto the Detail Section of the form frmStudMod and drop it into position. Don’t worry if it is not positioned correctly at the moment, you can reposition it later. Delete the caption on the subform. You will find this caption positioned on the top-left corner of the subform. Now you can place the subform in its final position. 48 If the values have not been set automatically enter student_id in these two fields By entering student_id in the Link Child Fields and Link Master Fields you set the reference between the source tables and query behind these two forms. When a student is chosen on the main form the subform will update automatically to show only those records in the tblStudMod table with matching student_id. When a student is entered into the database using frmStudMod and a module is added to his or her record the values in the student_id and module_id fields will be automatically entered in a new record in the tblStudMod table. The last thing to do is to size the forms as you did when you created the frmStudent and frmModule forms. Now try adding some modules to students’ records. 49 8.9 Deleting records Click this button to delete a record If you delete a record in the main form, you are deleting a record from the tblStudent table. Access will delete the corresponding records in the tblStudMod table, but will not delete the modules from the tblModule table. If you delete a record in the subform, you are only deleting a record from tblStudMod. Although the module’s details will no longer be displayed in the subform, nothing will be deleted from the tblModule table. Even if you delete all the records in the subform, you will not delete a module – you will simply have a module without any links to students. Go back to Forms tab and open the form Delete some of the records that you have just entered The picture below reminds you that it is important to notice where the cursor is before you click the Delete Record button. Q. The cursor is positioned in the Module field. If you delete this record what do you think will be removed from the table(s)? Q. In order to delete Malcolm Wilson from the database where should you position the cursor prior to clicking the delete button? Will you also delete the modules he is studying, or only the references pertaining to Malcolm? 50 Appendix 1: Data Types You can use the DataType property to specify the type of data stored in a table field. Each field can store data consisting of only a single data type. The DataType property uses the following settings. Setting Type of data Size Text (Default) Text or combinations of text and numbers, as well as numbers that don't require calculations, such as phone numbers. Up to 255 characters or the length set by the FieldSize property, whichever is less. Microsoft Access does not reserve space for unused portions of a text field. Memo Lengthy text or combinations of text and numbers. Up to 65,535 characters. (If the Memo field is manipulated through DAO and only text and numbers [not binary data] will be stored in it, then the size of the Memo field is limited by the size of the database.) Number Numeric data used in mathematical calculations. For more information on how to set the specific Number type, see the FieldSize property topic. 1, 2, 4, or 8 bytes (16 bytes if the FieldSize property is set to Replication ID). Date/Time Date and time values for the years 100 through 9999. 8 bytes. Currency Currency values and numeric data used in mathematical calculations involving data with one to four decimal places. Accurate to 15 digits on the left side of the decimal separator and to 4 digits on the right side. 8 bytes. AutoNumber A unique sequential (incremented by 1) number or random number assigned by Microsoft Access whenever a new record is added to a table. AutoNumber fields can't be updated. For more information, see the NewValues property topic. 4 bytes (16 bytes if the FieldSize property is set to Replication ID). Yes/No Yes and No values and fields that contain only one of two values (Yes/No, True/False, or On/Off). 1 bit. 51 Setting Type of data Size OLE Object An object (such as a Microsoft Excel spreadsheet, a Microsoft Word document, graphics, sounds, or other binary data) linked to or embedded in a Microsoft Access table. Up to 1 gigabyte (limited by available disk space) Hyperlink Text or combinations of text and numbers stored as text and used as a hyperlink address. A hyperlink address can have up to three parts: Each part of the three parts of a Hyperlink data type can contain up to 2048 characters. text to display — the text that appears in a field or control. address — the path to a file (UNC path) or page (URL). subaddress — a location within the file or page. screentip — the text displayed as a tooltip. The easiest way to insert a hyperlink address in a field or control is to click Hyperlink on the Insert menu. Lookup Wizard Creates a field that allows you to choose a value from another table or from a list of values by using a list box or combo box. Clicking this option starts the Lookup Wizard, which creates a Lookup field. After you complete the wizard, Microsoft Access sets the data type based on the values selected in the wizard. The same size as the primary key field used to perform the lookup, typically 4 bytes. Remarks Memo, Hyperlink, and OLE Object fields can't be indexed. Tip: Use the Currency data type for a field requiring many calculations involving data with one to four decimal places. Single and Double data type fields require floating-point calculation. The Currency data type uses a faster fixed-point calculation. Caution: Changing a field's data type after you enter data in a table causes a potentially lengthy process of data conversion when you save the table. If the data type in a field conflicts with a changed DataType property setting, you may lose some data. Set the Format property to specify a predefined display format for Number, Date/Time, Currency, and Yes/No data types. 52 Appendix 2: The Data Dictionary Every item you include within your database is an individual object, each with its own attributes. For example, when you create a form you place various objects on the form; labels, text boxes, buttons, etc. Each of these individual items, and the form itself, is defined by its attributes (length, height, position, data type, etc.). Some objects have different attributes depending on its function. This is similar to the properties of the data types we defined in when we created the tables for our sample database. A data dictionary is used to define and constrain every object in a database application. In order to properly document the database all parts of it should be defined and constrained before any construction is undertaken. A well documented application is easy to pass on to someone else to maintain or further develop. The new owner needs only to read the data dictionary and they should be able to understand the construction and constraints set at the time of initial design. It follows therefore that any additions or changes made by the new owner should also be documented in the data dictionary. The prime need in the data dictionary is to define the data types, tables, etc., including the field sizes, constraints and default values. We did this at the beginning of the course when we designed the data tables. Another fundamental need within a data dictionary is to clearly set out the rules for naming objects. Microsoft Access will give a default name to every object used in a database, but these are rarely useful for later referral. It is good practice to rename each object when you create it to conform to the rules you have defined in the data dictionary. Suggestions for a Naming Convention Controls are graphical user interface objects, such as text boxes, check boxes, scroll bars, or command buttons that let users control the program. You use controls to display data or choices, perform an action, or make the user interface easier to read. In Microsoft Access names of fields, objects and controls: Can be up to 64 characters long. Can include any combination of letters, numbers, spaces, and special characters except a period (.), an exclamation point (!), an accent grave (`), and brackets ([ ]). Cannot begin with leading spaces. Cannot include control characters (ASCII values 0 through 31). Cannot include a double quotation mark (") in table, view, or stored procedure names in a Microsoft Access project. When you name a field, control, or object, it's a good idea to make sure the name doesn't duplicate the name of a property or other element used by Microsoft Access; otherwise, your database can produce unexpected behaviour in some circumstances. For example, if you refer to the value of a field called Name in a table NameInfo using the syntax NameInfo.Name, Microsoft Access displays the value of the table's Name property rather than the value of the Name field. In order to correctly identify an object in a database it is desirable to prefix its name with a three letter identifier. Set out below are some suggestions for a standard method for doing this. Note that spaces have been removed in the examples shown, with each individual part of the name being delineated with an uppercase letter. Although you can include spaces in field, control, and object names, most examples in the Microsoft Access documentation show field and control names without spaces because spaces in names can produce naming conflicts in Microsoft Visual Basic for Applications in some circumstances. 53 Prefix Object Type Example tbl Table object tblStudent qry Query object qrySelectStudent frm Form object frmModule rpt Report object rptStudentRecord txt Textbox on a form or report txtStudentID lbl Label on a form or report lblStudentName cbo Drop-down combo box on a form cboModule lst List box on a form lstModule cmd Command button on a form cmdCloseForm chk Check box on a form chkShowRecord opt Options group on a form opt Level lin Graphical line on a form or report linDiv1 box Graphical rectangular box on a form or report boxBackMain 54