Вы находитесь на странице: 1из 56


Why Database?

Why should an Organisation choose to use an integrated database to store its operational
data? A general answer to this question is that a database system provides the
Organisation with centralised control of its data. This is in sharp contrast to the situation
that prevails in many enterprises, where typically each application has its own private files
in its own tapes and disks, so that the data is widely dispersed and therefore difficult to
control. The advantages of having the data in a centralised database is summarised

Redundancy can be reduced:

reduced In non-database systems each application or department
has its own private files resulting in considerable amount of redundancy of the stored
data. Thus storage space is wasted. By having a centralised database most of this can be
avoided. I do not say or suggest that all redundancy should be eliminated. Sometimes
there are sound business and technical reasons for maintaining multiple copies of the
same data. In a database system, however, this redundancy can be controlled.
Inconsistency can be avoided: This is really a corollary to the above point. When the
same data is duplicated and changes are made at one site which is not propagated to the
other site, it give rise to inconsistency. Then the two entries regarding the same data will
not agree. At such times the data is said to be inconsistent. So if the redundancy is
removed chances of having inconsistent data is also removed.
The data can be shared:
shared The existing applications can share the data in a database.
Standards can be enforced:
enforced With the central control of the database, the database
administrator can enforce standards.
Security restrictions can be applied:
applied Having complete authority over the operational data
the database administrator can ensure that the only means of access to the database is
through proper channels and can define authorisation checks to be carried out whenever
access to sensitive data is attempted. Different checks can be established for each type of
access (retrieve, modify, delete, etc.) and to each piece of information in the database.
Integrity can be maintained:
maintained Integrity means that the data in the database is accurate.
Centralised control of the data helps in permitting the administrator to define integrity
constraints to the data in the database.
Conflicting requirements can be balanced:
balanced Knowing the overall requirements as opposed
to the individual requirements, the database can be structured to provide an overall
service that is best for the Organisation.

Characteristics of Database Management Systems

Data storage techniques have evolved through several stages, and all stages are still to
be found today, the primitive ones mainly on small systems or mini computers. The term
database can into popularity in the 1970s. Prior to that the data processing world had
talked about files of data. Some of the most important characteristics of a database are:

Data Independence
Speedy handling of spontaneous information requests
Versatility in representing relationships between data items.
Security protection
Real-time accessibility

As the employment of better data management software spreads, these characteristics

spread with it.
Database Management System For Private Circulation only

Relational Database Management Systems (RDBMS)

Development of Database Management Systems (DBMS), Relational Database

Management Systems(RDBMS), Structured Query Languages (SQLs), etc. are so closely
intertwined that some amount of repetition becomes unavoidable. The foundations of
Relational Database technology were laid by the Dr. E.F.Codd, who in his paper 'A
Relational Model of Data for Large Shared Data Banks' laid the basic principles of the
RDBMS. Codd was at that time working for IBM at their San Jose Research Lab in
California. He laid down certain principles of database management, referred to as
relational model. These principles were soon applied to experimental systems, and a start
was made on the design of a database language that would interact with such systems

At present there are many implementations of the relational technology. At the mainframe
end there are DB2, ORACLE, Ingress all supporting different dialects of SQL. Relational
systems are now available in all sizes and shapes and for all sizes of computers.

RDBMS Terminology

The relational model, is an abstract theory of data that is based on the mathematical
theory whose principles were laid down by Dr.E.F. Codd. The relational model of Codd
used certain terms and principles, which were not familiar in the data processing circles at
that time. The terms that were used to describe the database properties and functions
lacked the precision necessary for the formal list of the relational term and their
corresponding informal equivalent(s).

Formal Relational term Informal equivalent (s)

Relation Table
Tuple Row, Record
Attribute Column, field
Primary key Unique identifier

The Relational Database Management Systems, as said above, are based on the
relational model. The relational Model, in turn, is a way of looking at data - that is, it is a
prescription for how to represent and manipulate data. More precisely, the relational
model is concerned with three aspects of data: data structure, data integrity, and data
Codd's Rules.
1. Information Rule:
Rule All information in a relational database including table names,
column names are represented by values in tables. This simple view of data speeds
design and learning. User productivity is improved since knowledge of only one language
is necessary to access all data such as description of the table and attribute definitions,
integrity constraints. Action can be taken when the constraints are violated. Access to
data can be restricted. All these information are also stored in tables.
2. Guaranteed Access Rule:Rule Every piece of data in a relational database, can be
accessed by using a combination of a table name, a primary key value that identifies the
row and a column name which identifies a cell User productivity is improved since there is
no need to resort to using physical pointers or addresses. It also provides data
independence and make it possible to retrieve each individual piece of data stored in a
relational database by specifying the name of the table in which it is stored, the column
and the primary key which identifies the cell in which it is stored.
3. Systematic Treatment of Nulls Rule:
Rule The RDBMS handles records that have unknown
or inapplicable values in a pre-defined fashion. Also, the RDBMS distinguishes between
zeros, blanks and nulls in the records and handles such values in a consistent manner
that produces correct answers, comparisons and calculations. Through the set of rules for
Database Management System For Private Circulation only

handling nulls, users can distinguish results of the queries that involve nulls, zeros and
blanks. Even though the rule doesn't specify what should be done in the case of nulls, it
specifies that there should be a consistent policy in the treatment of nulls.
4. Active on-
on-line catalog based on the relational
relational model:
model The description of a database
and its contents are database tables and therefore can be queried on-line via the data
manipulation language. The Database Administrator's productivity is improved since the
changes and additions to the catalog can be done with the same commands that are used
to access any other table. All queries and reports can also be done as any other table.
5. Comprehensive data sub- sub-language rule:
rule The RDBMS may support several languages.
But at least one of them should allow the user to do all of the following: define tables and
views, query and update data, set integrity constraints, set authorisations and define
transactions. User productivity is improved since
there is just one approach that can be used for all database operations. In a multi-user
environment the user does not have to worry about the data integrity and such things,
which will be taken care by the system. Also, only users with proper authorisation will be
able to access data.
6. View Updating Rule:
Rule Any view that is theoretically updatable can be updated using the
RDBMS. Data consistency is ensured since the changes made in the view is transmitted
to the base-table and vice-versa.
7. High-
High-Level Insert, Update and Delete:
Delete The RDBMS supports insertion, updation and
deletion at a table level. The performance is improved since the commands act on a set of
records rather that one record at a time.
8. Physical data Independence:
Independence The execution of ad hoc requests and application
programs is not affected by changes in the physical data access and storage methods.
Database administrators can make changes to the physical access and storage method,
which improve performance and do not require changes in the application programs or
requests. Here the user specifies what he wants and need not worry about how the data
is obtained.
9. Logical Data Independence:
Independence Logical changes in tables and views such as adding,
deleting columns or changing field lengths need not necessitate modifications in the
programs or in the format of ad hoc requests. The database can change and grow to
reflect changes in reality without requiring the user intervention or changes in the
applications. For example adding an attribute or column to the base table should not
disrupt the programs or the interactive commands that have no use for the new attribute.

10. Integrity Independence:

Like table and view definitions, integrity constraints are stored in the on-line catalog and
can therefore be changed without necessitating changes in the application programs.
Integrity constraints specific to a particular Relational Database must be definable in the
relational data sub-language and storable in the catalog. At least the Entity integrity and
integrity must be supported.
11. Distribution Independence
ependence Application programs and ad hoc requests are not
affected by changes in the distribution of physical data. This improves systems reliability
since application programs will work even if the programs and data are moved in different
12. Non-
on-subversion Rule:
Rule If the RDBMS has a language that accesses the information of
a record at a time, this language should not be used to bypass the integrity constraints.
This is necessary for data integrity.

According to Dr. Codd, a Relational Database Management System (RDBMS) must be

able to manage the databases entirely through its relational capabilities.
Database Management System For Private Circulation only

Data Modeling

Data modeling is the process of building database structures to store data. This involves
analysis in first identifying which data must be stored and then deciding how best to store
it. This step is crucial, because any application ultimately depends on its data structures.
If the data structures are poorly designed the application will start from a poor foundation.
This will require a lot more work to create a useful and efficient application, if it can be
done at all.
Principles of Normalization

Normalization is a formal process of developing data structures in a manner that

eliminates redundancy and promotes integrity. Data Normalization is a comer stone of the
relational theory. Many people do not consider a set of data structures to be relational
unless it is fully normalized. There are five steps to Data Normalization, which are called
the normal forms. Each normal form builds upon the last and functions as both a process
and a criterion. For example, a database structure can be developed to the third normal
form or can be said to satisfy the second normal form. Before discussing the normal
forms, there are two concepts required by normal forms that integral to Data Modeling:
Keys and Relationships.


A key uniquely identifies a row in a table. There are two types of keys: intelligent keys and
non- intelligent keys. An intelligent key is based upon data values such as a date, a last
name or a combination of values. A non-intelligent key is completely arbitrary, having no
function or meaning other than identification of the row.

Intelligent keys are problematic because the key value must be changed to reflect
changing data values. An updateable key presents its own problems, because all related
tables must be updated every time the key is updated. As a general rule, intelligent keys
must never be used, but it is not always possible to do that.

A primary key is a column in the table whose purpose is to uniquely identify records from
the same table. A foreign key is a column in a table that uniquely identifies records form a
different table. Primary and foreign keys therefore have a symbiotic relationship, in which
the foreign key is used to store values of another table's primary key to describe the
relationship between data from different tables.


There are three possible relationships between related tables:

1. one-to-one
2. one-to-many
3. many-to-many

Relational Databases are designed to work most effectively with one-to-many

relationships between tables, expressed using primary and foreign keys. Defining a
column as a primary key in the database will ensure that no duplicate values are
contained in that column. In other words, primary key will be unique.

One-to-one relationships are rare, because data elements related in this way are normally
placed in the same table. When a one-to-one relationship is desired, it can be expressed
simply as a one-to- many relationship using primary and foreign keys.
Database Management System For Private Circulation only

One-to-many relationships are most common. A primary key is the 'one' side of the
relationship, and the foreign key is the 'many' side of the relationship. A primary key value
is unique in its own table. Each primary key may have any number of foreign keys using
the same value, in any number of tables, or each pair of primary and foreign key columns
is a one-to-many relationship. The data values stored in these columns determine which
rows from the table containing the foreign key column are associated with an individual
row in the table containing the primary key column. The foreign key value refers to one,
and only one, value in the table containing the primary key. The primary key value may be
referenced by multiple foreign keys. This is how one-to-many relationships are expressed
and maintained by the database. The database can perform special operations on
primary and foreign key relationship between tables, including the ability to delete all rows
in a table containing a foreign key value when the associated primary key row is deleted
or to restrict deletion of a row containing a primary key that has references in another
table. Defining primary and foreign key columns in the database promotes data integrity.

Many-to-many relationships are problematic and cannot be adequately expressed directly

in a relational database. Many-to-many relationships are usually expressed using
intersection tables. An intersection table contains two or more foreign keys, relating the
primary key values of two or more tables to each other. The role of an intersection table is
to convert the many-to-many relationship into two one-to-many relationships that can be
easily handled by the database.

The First Normal Form - Elimination of Repeating Groups

A repeating group is a set of columns that store similar information that repeats in the
same table. Consider the following table, which contains the contact tracking information:


CONTACT_ID Number Integer

NAME Text 20
CONTACT_DATEI Date Medium Date
CONTACT_DATE2 Date Medium Date

This data structure contains a repeating group of the date and description of two
conversations. The only advantage of designing the table like this is that it avoids the
need for a relationship. But the disadvantages are many:

• This structure limits the number of conversations to two, which will create problems
when more than two conversations need to be stored.
• This structure also makes it difficult to do any kind of meaningful searching using the
columns, for example to locate a conversation on a specific date (here both the date
columns has to be searched which will result is a clumsy SQL code).

To eliminate the repeating group, the group is moved to another table, which is then
related to the parent table. The primary key of the parent table (CONTACT_ID) is stored
in the second table. Moving the repeating group into another table allows any number of
conversations to be recorded and searched easily. The primary and foreign key
relationships are defined to ensure that no conversations are recorded that do not relate
to a contact. The tables contents for this is given below:
Database Management System For Private Circulation only


CONTACT_ID NumberInteger Primary Key
NAME Text 20


CONTACT_ID Number Integer
CONTACT_DATE Date Medium Date

After creation of the tables set relationship with CONTACT_ID in these tables.

Every table should have a primary key, and each set of repeating groups should appear in
its own table. When these criteria are satisfied, the first normal form is satisfied.

The Second Normal Form - Elimination of Redundant Data

Redundant data is data that is expressed multiple times unnecessarily or depends only on
part of a multi-value key. In other words, when a column's value is dependent upon the
value of one column in the table, but not another, it is considered redundant. For example:


EMP_NO Number Long Integer
NAME Text 20
F_NAME Text 20
DEPT_CODE Number Integer

This table contains redundant data, namely the department description which depends
only on the DEPT_CODE and does not vary based on the value of the EMF_NO, which is
the primary key of the table. So by storing the department code and description in a
different table the redundancy is eliminated.


EMP_NO Number Long Integer Primary key
NAME Text 20
F_NAME Text 20
DEPT_CODE Number Integer


DEPT_CODE Number Integer (Primary Key)

The Third Normal Form - Eliminate columns not dependent on the key

The columns in each table should be a group of columns in which the data in each column
contributes to the description of each row in the table. For a given row with a unique key,
each column appearing in that row should contribute to the description of that row. For
example in the following table, the columns NAME contribute to describing a specific
contact using the primary key CONTACT'_ID. But, the COMPANY_NAME and
COMPANY_LOCATION does not contribute to describing the record with a given
CONTACT_ID, since it identifies an individual and not a company.
Database Management System For Private Circulation only


CONTACT_ID Number Integer
NAME Text 20

So unless the location of the company differs on an individual basis, this column in not
dependent on the key value and should be removed to another table.


CONTACT_ID Number Integer Primary Key
NAME Text 20


COMPANY_ID Text 5 Primary Key

When all the columns in a table describe and depend upon the primary key, the table is
said to satisfy the third normal form.

Fourth Normal Form - Isolate Independent Multiple Relationships

A group of tables that satisfies the first, second and third normal forms is sufficiently well
designed. However, isolating independent multiple relationships will further improve the
data model when one-to-many and many-to-many relationships between tables are
involved. In other words, no table should contain two or more one-to-many or many-to-
many relationships that are not directly related to the key.

Consider the following example:


CONTACT_ID Number Integer Primary Key
NAME Text 20


CONTACT _ID Number Integer

Even though this is not a violation of the third normal form this data structure makes it
difficult to store a phone number of a contact without a company and makes it impossible
to store multiple phone numbers for the same contact without repeating the company
information. The Fourth Normal Form is violated because there are two independent
relationships represented in the COMPANY table: one between CONTACTS and
COMPANIES and another between CONTACT and PHONE_NUMBER, which should be
avoided. This can be achieved as follows:


CONTACT_ID Number Integer Primary Key
NAME Text 20


CONTACT _ID Number Integer
Database Management System For Private Circulation only



CONTACT _ID Number Integer

This allows companies and phone numbers to have independent, one-to-many

relationships with CONTACTS table, which satisfies the fourth normal form.

The Fifth Normal Form - Isolate Semantically Related Multiple Relationships

The chances that you will ever get to use the fifth normal form are very few, because it
requires semantically related multiple relationships, which are rare. Semantically related
multiple relationships are two or more relationships among tables that are related closely
enough so that they can be resolved into a single relationship. Fifth normal form specifies
that they remain separate.

Consider the chemical analysis labs, which tests products of various companies. Three
tables exist, LAB, PRODUCT and COMPANY. Companies can offer one or more
products, labs can test one or more products from one or more companies and a product
can be tested in one or more labs and can be offered by one or more companies.
Whenever a lab is equipped to test a product from any company, the lab is equipped to
test the same product from all companies. If a lab is equipped to analyze a product from a
given company, this can be recorded in a table with the following structure:


LAB_ID Number Long Integer

PRODUCT_ID Number Long Integer
COMPANY_ID Number Long Integer

The table contains three foreign keys expressing two relationships: the relationship
between LABS and PRODUCTS and that between LABS and COMPANIES. The
relationships are semantically related because they can be expressed using the same
table. In other words, the relationship between PRODUCTS and COMPANIES is implied
and expressed in this table.

There is nothing wrong with the above data structure, but, it does not satisfy the fifth
normal form and more entries are required in the table than necessary if the relationship
are separated. Because a lab can test the same product for all companies who offer a
given product, the following structure will be better:


LAB_ID Number Long Integer
PRODUCT_ID Number Long Integer
LAB_ID Number Long Integer
PRODUCT_ID Number Long Integer

This allows the products that a given lab can test to be recorded and the companies
whose products can be tested by a lab to be recorded with fewer entries. For example if
lab A is newly equipped to do a spectroscopic analysis of products A, B and C offered by
companies X and Y, the new structure requires five entries, 3 in the LAB_LPRODUCT
Database Management System For Private Circulation only

table and two in LAB_COMPANY table, to express this. To achieve the same, with the
original structure we will require six entries.

The fifth normal form is not frequently invoked for the reason that the situation simply
does not arise frequently.

Principles of Denormalization

No major application will run in Third Normal Form. This is probably as heretical a
statement as can be made in the face of modern relational technology, but it needs to be
said. Perhaps, as CPUs get faster and parallel processing architecture is better exploited,
this will no longer be true; more likely the size of major applications will also increase.
Demand for information and analysis will probably continue to outpace the ability of
machines to process it in a fully normalized fashion.

Now, before cries for another inquisition begins, this needs to be explained. The issue of
normalization has several components. This section does not challenge the relational
model or the process of Normalization, which is an excellent and rational method of
analyzing data and its fundamental relationships. This section challenges the following

• Normalization completely rationalizes data.

• Normalization accurately maps how humans work with data
• Normalized data is the best representation of data.
• Data stored non-redundantly will be accessed faster than data stored many times.
• Normalized tables are the best way to store data.
• Referential integrity requires fully normalized tables.

Normalization is simply a method to analyze elements of data and their relationships and
the relational model is the theoretical superstructure that supports the process. Together,
these provide a way of viewing the world of data. But they are not the only correct or
useful ways to view the data. In fact, in a complex set of relationships, even the third
normal form becomes insufficient rather quickly. Higher forms have been conceived to
cope with these more difficult relations, although they are not used outside of academia.
Theorists readily acknowledge that these also fail completely model reality.

When analyzing the data of a business, normalizing the data to at least the third normal
form assures that each non-key column in each table is dependent only on the whole
primary key of the table. If the data relationships are complex enough, normalizing to a
higher form does a fine, if not complete, job of giving you a deep understanding of data
and of relations between the various elements that must be protected and sustained as
the application and database are built.
For a major application, however, or even a simple application where tasks do not readily
map to fully normalized tables, once the analysis is complete, the design process may
need to denormalize some of the tables in order to build an application that is responsive,
maps to the user's tasks and will actually complete its processing in the time windows

Denormalization is the opposite of Normalization. It is the process of increasing

redundancy in the database either for convenience or to improve performance. However,
proper denorrnalization takes place after a model has been fully normalized.
Denormalization is usually done for convenience and to improve performance.
Denormalisation of frequently performed operations or calculations can be used to
improve performance. For example in accounting packages there will be the daily
transaction table which contains the details of each and every transaction for every head
Database Management System For Private Circulation only

of accounts. But usually there will be a monthly transaction summary which will only have
the monthly aggregate of all the transactions under each head of account. The data
contained in the monthly transaction table is completely redundant, because everything
can be derived form the daily transaction table using SQL statements. But the monthly
summary information is very frequently used and calculating it each and every time will
slow down the application resulting in poor response times. Unfortunately, the updates to
the daily transaction table are not automatically reflected in the summary table, unless
database triggers are created to ensure that data integrity is maintained. So before doing
a denormalisation, you should make sure that the costs of maintenance do not outweigh
the benefits.

It is very important to understand that the design of data structures will have a profound
impact on the performance and structure of the front-end application and reports.
Although it is possible to 'work around' a poor data model with a great deal of code, it is
not desirable to do so. Ideally an application should start with a fully normalized data
structure, which will serve as a firm foundation.

However, any recommendations attempting to produce better response will have to differ
from application to application. They will also differ over time as query optimization
methods improve, and as more and more CPU power is pushed out to the peripheral
devices in the computer system and network. Benchmarking your application on your
system is the only way to truly optimize your database.

To sensibly build an application you must strike a balance among three primary factors:
ease of use, performance and maintainability. In a perfect world these would all be
maximized. But in a world where projects have limited development time frames,
machines have limited power, and ease of use essentially means additional program
complexity, not favouring one factor at the expense of others is a challenge.

The two integrity rules for the relational models are
1. Entity Integrity
No attribute participating in the primary key of a base relation is allowed to contain any
nulls. Primary key performs the unique identification function in a relational model. Thus a
null primary key value within a base relation would be like saying that there was some
entity that had no known identity. An entity that cannot be identified is a contradiction in
terms, hence the name entity integrity.

2. Referential Integrity

If base relation/table includes a foreign key (FK) matching the primary key (PK) of some
other base relation, then every value of FK in the first table/relation must either be equal
to the value of PK in some tuple of the second table/relation or be wholly null (that is each
attribute value participating in that FK value must be null). Or in other words a given
foreign key value must have matching primary key value in some tuple of the referenced
relation if that foreign key value is non null. Sometimes, it is necessary to permit foreign
keys to accept nulls. Here it must be noted that the null are of the variety 'value does not
exist' rather than 'value unknown'.

Database Management System For Private Circulation only

Unlike other application software MS Access ask for the filename (database name) as
soon as you try to create a new file. This database name will crate a database workspace
in which we can create several objects such as Table, Query (View), Forms, Modules,
Pages, Reports, etc. each object in this work space has its own importance and functions.
The default file extension of Microsoft Access is ‘..MDB’ (M
Microsoft DataB
Microsoft Access obeys several features of RBMS Codd rules. Here also data are stored
in tables. The previous versions of DBMS like dBase, FoxPro, etc store records in flat
files. For extracting records from table SQL language is required.


In table tab you can create tables which are used for storing records. In Access all records
are kept in Tables. All other objects are used to manage, manipulate and extract records
from table. You can create several Tables in a database. While creating table apply
normalization techniques. Tables should be properly related. You should properly enforce
referential integrity check. By enforcing this we can avoid orphan records.


Queries are used to create user views, extract records based on conditions, calculating
and updating values in table etc. queries are only a structure. It doesn’t contain any
record. While running a query it will extract records from table. Query can be classified as
Select Query, Parameter Query, Update Query, Crosstab Query, Make-table Query,
Append Query, Duplicate Query, Unmatched Query, Delete Query and Union Query.

Forms are used for data entry operations. We create several types of forms based on the
purpose we can create columnar forms (data entry), Tabular forms for viewing and
analyzing records. We can design forms as well as create forms by using wizard.

Pages are also front end tools in access. We can create html pages and use web
browsers to open database. It is quite suitable for multi user data entry environment.

Creating reports we can use report tab. The Report tool of ms access is a power full and
flexible one. We can categorize, group, sort and organize data in report. Multi level
grouping is possible in reports.

These are small built in facility or programme to perform certain type of generic operations
such as calculating and assigning values in forms controls, displaying messages etc.

Modules are used for writing visual basic application coding. We can define functions
(methods), procedures, global variables etc in module session.

Field data types available in Access (MDB)

Note The information in this topic applies only to a Microsoft Access database (.mdb).

The following list summarizes all the field data types available in Microsoft Access, their
uses, and their storage sizes.
Database Management System For Private Circulation only

Use for text or combinations of text and numbers, such as addresses, or for numbers that
do not require calculations, such as phone numbers, part numbers, or postal codes.
Stores up to 255 characters. The FieldSize property controls the maximum number of
characters that can be entered.
Use for lengthy text and numbers, such as notes or descriptions.
Stores up to 65,536 characters.
Use for data to be included in mathematical calculations, except calculations involving
money (use Currency type).
Stores 1, 2, 4, or 8 bytes; stores 16 bytes for Replication ID (GUID). The FieldSize
property defines the specific Number type.
Use for dates and times.
Stores 8 bytes.
Use for currency values and to prevent rounding off during calculations.
Stores 8 bytes.
Use for unique sequential (incrementing by 1) or random numbers that are automatically
inserted when a record is added.
Stores 4 bytes; stores 16 bytes for Replication ID (GUID).
Use for data that can be only one of two possible values, such as Yes/No, True/False,
On/Off. Null values are not allowed.
Stores 1 bit.

OLE Object
Use for OLE objects (such as Microsoft Word documents, Microsoft Excel spreadsheets,
pictures, sounds, or other binary data) that were created in other programs using the OLE
Stores up to 1 gigabyte (limited by disk space).
Use for hyperlinks. A hyperlink can be a UNC path or a URL.
Stores up to 64,000 characters.
Lookup Wizard
Use to create a field that allows you to choose a value from another table or from a list of
values using a combo box— -choosing this option in the data type list starts a wizard to
define this for you.
Numeric Field size
Setting Description Decimal Storage
precision size
Byte Stores numbers from 0 to 255 (no fractions). None 1 byte
Decimal Stores numbers from –10^38–1 through 10^38–1 (.adp) 28 12bytes
Stores numbers from –10^28–1 through 10^28–1 (.mdb)
Integer Stores numbers from –32,768 to 32,767 (no fractions). None 2 bytes
Long (Default) Stores numbers from –2,147,483,648 to None 4 bytes
Integer 2,147,483,647 (no fractions).
Single Stores numbers from 7 4 bytes
–3.402823E38 to –1.401298E–45
for negative values and from
1.401298E–45 to 3.402823E38 for positive values.
Double Stores numbers from 15 8 bytes
–1.79769313486231E308 to
Database Management System For Private Circulation only

for negative values and from
4.94065645841247E–324 to
1.79769313486231E308 for positive values.
Replica- Globally unique identifier (GUID) N/A 16 bytes
tion ID


This property to make data entry easier and to control the values users can enter in a text
box control. Input masks are helpful for data-entry operations such as an input mask for a
Phone Number field that shows you exactly how to enter a new number: (___) ___-____.

The InputMask property can contain up to three sections separated by semicolons (;).
Section Description
First Specifies the input mask itself; for example, !(999) 999-9999. For a list of
characters you can use to define the input mask, see the following table.
Second Specifies whether Microsoft Access stores the literal display characters in the table
when you enter data. If you use 0 for this section, all literal display characters (for
example, the parentheses in a phone number input mask) are stored with the
value; if you enter 1 or leave this section blank, only characters typed into the
control are stored.
Third Specifies the character that Microsoft Access displays for the space where you
should type a character in the input mask. For this section, you can use any
character; to display an empty string, use a space enclosed in quotation marks (" ").

When you create an input mask, you can use special characters to require that certain
data be entered (for example, the area code for a phone number) and that other data be
optional (such as a telephone extension). These characters specify the type of data, such
as a number or character that you must enter for each character in the input mask.

You can define an input mask by using the following characters.

Character Description
0 Digit (0 to 9, entry required, plus [+] and minus [–] signs not allowed).
9 Digit or space (entry not required, plus and minus signs not allowed).
# Digit or space (entry not required; spaces are displayed as blanks while in
Edit mode, but blanks are removed when data is saved; plus and minus signs
L Letter (A to Z, entry required).
? Letter (A to Z, entry optional).
A Letter or digit (entry required).
a Letter or digit (entry optional).
& Any character or a space (entry required).
C Any character or a space (entry optional).
.,:;-/ Decimal placeholder and thousand, date, and time separators. (The actual
character used depends on the settings in the Regional Settings Properties
dialog box in Windows Control Panel).
< Causes all characters to be converted to lowercase.
> Causes all characters to be converted to uppercase.
! Causes the input mask to display from right to left, rather than from left to
right. Characters typed into the mask always fill it from left to right. You can
include the exclamation point anywhere in the input mask.
\ Causes the character that follows to be displayed as the literal character (for
example, \A is displayed as just A).
Database Management System For Private Circulation only

Note Setting the InputMask property to the word "Password" creates a password-entry
control. Any character typed in the control is stored as the character but is displayed as an
asterisk (*). You use the Password input mask to prevent displaying the typed characters
on the screen.
For a control, you can set this property in the control's property sheet. For a field in a
table, you can set the property in table Design view (in the Field Properties section) or in
Design view of the Query window (in the Field Properties property sheet ).
If you move text from a field for which you've defined an input mask onto the Clipboard,
the literal display characters are copied, even if you have specified that they not be saved
with data.
Note Only characters that you type directly in a control or combo box are affected by the
input mask. Microsoft Access ignores any input masks when you import data, run an
action query, or enter characters in a control by setting the control's Text property in
Visual Basic or by using the SetValue action in a macro.
When you've defined an input mask and set the Format property for the same field, the
Format property takes precedence when the data is displayed. This means that even if
you've saved an input mask, the input mask is ignored when data is formatted and
displayed. The data in the underlying table itself isn't changed; the Format property affects
only how the data is displayed.
The following table shows some useful input masks and the type of values you can enter
in them.
Input mask Sample values
(000) 000-0000 (206) 555-0248
(999) 999-9999 (206) 555-0248
( ) 555-0248
(000) AAA-AAAA (206) 555-TELE
#999 –20
>L????L?000L0 GREENGR339M3
MAY R 452B7
>L0L 0L0 T2F 8M4
00000-9999 98115-
>L<?????????????? Maria
SSN 000-00-0000 SSN 555-55-5555
>LL00000-0000 DB51392-0493

Start⇒All Programs/Programs⇒
Programs/Programs⇒Microsoft Access
Choose Blank database option button (File⇒New⇒Blank Database)⇒OK
Give a Database Name⇒Create
Now you can see the Database window which contains several objects as mentioned
Creating TableDouble click on the Create Table in Design View (New⇒Design
In the Table Design pane type Filed Names, Select Data Type and in Field Properties
pane give proper Filed Properties such as Filed Size (Width), Format, Validation Rule etc.
Filed Name: - you should give a meaningful and short name for the filed based on the
type of value in which you are going to type (store). Eg: - EmpName for Name of
employee, DateBirth for Date of Birth etc. MS Access supports space in field names, but it
is better to avoid space in between words in a filed name. To identify words use capital
letters at the beginning of each word.
Database Management System For Private Circulation only

Field Description is meant for marking your commend.

Filed size: - no of characters which can be accommodated in this filed.
Format: - Whether Capital letters, Small letters, Currency format or comma separated
format etc.
Input mask: - See page 14
Caption: - To display a Label as filed title when we take datasheet view
Default value: - a value which will appear automatically in the new records row when we

take data sheet view

Validation Rule: - for adding a constraint while entering data. For example BasicPay
should be grater than or equal to 4500 etc.
Validation Text: - A message which will display when the validation rule is violated.
Required: - Yes means data entry is compulsory, No means you can skip this filed while
entering data.
Allow zero length: -If Required property is ‘Yes’ this is ‘No’, if Required property is ‘No’ this
is ‘Yes’. To mention whether this field contains Null value or not.
Indexed: - is used to determine whether sorting is required or not. This field is also used
for specifying whether duplicate values are allowed in the filed or not.
Unicode compression: - whether compression enable for Hyperlink and memo fields.
IME Mode: - You can specify the Kanji Conversion Mode when the focus shifts to control
by setting the IMEMode property. If set to No Control (default) the setting before the focus
shifted to that control is used. For any other setting, the Kanji Conversion Mode setting for
that control is used. For example, if the IMEMode property is set to Off, the Kanji
Conversion Mode is turned off, and if the IMEMode
IMEMode property is set to On, the Kanji
Conversion Mode is turned on. The Kanji Conversion Mode automatically changes each
time the focus shifts between controls.
IME Sentence Mode: - You can use the IMESentenceMode property to specify or
determine the IME Sentence Mode of fields of a table or controls of a form that switch
when the focus moves

SmartTags: - Returns a SmartTags collection that represents the collection of smart tags
that have been added to a control. Smart tag actions are processes that are programmed
into smart tags that allow users to perform certain functions related to the smart tag. For
example, one action for a smart tag might be to access a Web site, while another action
Database Management System For Private Circulation only

inserts contact information from Microsoft Outlook, while yet another action displays a
map and driving directions.
Input Method Editor (IME)
The feature or some of the options described here are only available if support for
Japanese, Simplified Chinese, Traditional Chinese, or Korean is enabled through
Microsoft Office Language Settings.

Now create a table based on the following exercise. Don’t alter the default settings of field
properties, until you are requested to do so in the exercise, other wise leave it as such.

MS Access Exercise – I

Open Microsoft Access from Programs menu. Select ‘Blank Access Database’ radio
button from the ‘Microsoft Access’ dialog box. Then click OK button. Now you are
prompted for the Database name. Give a suitable name for your database say “Sample”.
Then click Create button. This will create “Sample
Sample MDB” database.
Now from the Objects sheet tab in the ‘Database window’ titled “Sample” choose table
Then db click on the ‘Create
Create Table in Design view’
view option OR click on the New button and
select the ‘Design View’ from the ‘New Table’ dialog box. By using the following
information you create the Fields (Attributes) properly. Use ‘F6’ function key for switching
between the ‘field property’ pan and ‘design pan’ choose proper filed property from the
table given below.
Field Name Data Type Description
EmpCode Text Employee code as Alphabets
EmpName Text Name in capital letters, Initials
at end
Sex Text M or F
Designation Text
DateofBirth Date/Time
Caste Text
BasicPay Number

Field Properties. (Choose corresponding property from the following table)

Field Format Default Validation Required Index
size Value Rule
5 Yes Yes (No
25 > Yes No
1 > M M or F Yes No
20 > No No
3 > OT SC or ST No No
or OT or
Integer Between
1500 and
Type appropriate ‘Validation
Validation Text’ for Validation rules. Say “Type M for Male or F for
Female” etc.
Save the Table and Give a Name “Salary Salary”.
Salary Open the table and enter more than 20
records in the table. Take the design of the table. Add two more fields “DateJoin”
(Date/Time), “Remarks” (Memo) and give suitable properties for them. Again reopen the
table and edit the fields.
Database Management System For Private Circulation only

Sample Data (Ref 2 Tables for full details)

Emp EmpName Sex Designation
E01 Krishnan Nair C M Section Officer
E02 Mohan Boss VK M Assistant
E03 John B Mathew M Asst.Professor
E04 Vijayan D M Gardener
E05 Sreekumari Amma P F Typist
E06 Viswambharan MR M Assistant
E07 Oommen Mathew M Asst.Professor
E08 Vasudevan PN M Driver
E09 Venkitachalam VH M Section Officer
E10 Neena Joseph F Asst.Professor
E11 Poulose AP M Roneo Operator
E12 Janardhanan Nair N M Gardener
E13 Raghavan PK M Peon
E14 Sathyaseelan S M Peon
E15 Rajappan E M Peon
E16 Chandrasekharan KP M Peon
E17 Sasidharan Nair KB M Roneo Operator
E18 Lonappan CP M Section Officer
E19 Thresia Ikkaraparambil F Sweeper
E20 Parthan K M Typist
E21 Ushakumari DS F Confidential Assistant
E22 Chandrika DS F Confidential Assistant
E23 Dharam Veer M Director
E24 Maya Muraleedharan R F Lecturer
E25 Abdul Vahid M Deputy Director
E26 Sulochana Devi S F Peon
E27 Lalitha KP F Lecturer
E28 Leelamma KP F Lecturer
E29 Anil Kumar C M Accounts Officer
E30 Vineetha S F Research Assistant

EmpCode DateBirth Caste BasicPay DateJoin

E01 08/Jul/57 OT 9850 06/Apr/80
E02 06/May/64 OT 7000 05/Apr/87
E03 01/Mar/59 OT 18450 05/Apr/84
E04 15/Jan/70 SC 4750 22/Oct/96
E05 05/Apr/73 OT 5250 04/May/95
E06 03/Aug/68 SC 6500 03/Jan/90
E07 08/Mar/63 OT 17650 08/Nov/90
E08 29/Feb/64 ST 5250 16/Apr/85
E09 08/Jul/60 OT 9650 08/May/87
E10 07/Dec/64 OT 16450 05/Apr/89
E11 29/Apr/71 OT 5425 06/May/90
E12 31/May/72 ST 4250 11/Sep/99
E13 07/Jul/67 SC 5525 28/Mar/90
E14 19/Apr/68 SC 5345 20/Apr/92
E15 03/Aug/74 ST 5120 21/Jun/00
E16 08/May/73 OT 4870 24/Jul/01
E17 04/May/64 OT 5100 08/May/92
Database Management System For Private Circulation only

E18 06/May/56 OT 9100 05/Jan/77

E19 08/Aug/68 OT 4500 06/Apr/87
E20 27/Jul/69 OBC 4800 08/May/92
E21 01/Jan/68 SC 5845 02/Jan/95
E22 23/May/65 ST 6250 20/Jun/87
E23 31/May/61 OT 28400 02/Jul/86
E24 08/Apr/79 OT 9450 09/Sep/03
E25 28/Apr/57 OBC 15245 27/Feb/78
E26 16/Jun/79 OBC 4650 19/Aug/04
E27 06/May/77 OBC 8900 14/Nov/03
E28 05/Jul/80 OT 8750 25/Aug/04
E29 01/Jan/60 OBC 14250 08/May/85
E30 29/Feb/76 OT 8750 15/Sep/03

MS Access Exercise –II

Create a new database “PayRoll
PayRoll and design a table “Designation
Designation in it with the following
Field Name Field Type Field Size Description
DesigCode Text 5 Primary key*
Designation Text 30

*For selecting Primery key property choose the corresponding filed name and Click Edit
⇒ Primary key OR Primary Key button in toolbar OR Rt. click and choose Primary Key.
Save the table as Designation.

Create one more table “Personnel” in the same database with the following details
Give Proper Validation Rule, Validation Text, Format, Default Value as described in
Exercise 1
Field Name Field Type Field Size Description
EmpCode Text 5 Primary Key
EmpName Text 25
EmpAddress Text 200
DateBirth Date/Time
DateJoin Date/ime
Sex Text 1
Designation Text 5 Foreign Key
Gazatted Yes/No
Caste Text 3
BasicPay Number Integer
Phone Text 15 Inputmask(####)-###########
Remarks Memo
Establishing Relationships between tables.
1. Close All Design/Data Sheet view of table, if any
2. Tools⇒Relationships
3. Select required tables (Hold down shift/Ctrl for multiple selections).
4. Add (only once)
5. Close Show Table Dialog box. (Rt Click on the filed list pane and choose show
table for the dialog box again)
6. Click and Drag Primary key (Bold) filed from Master Table
(Designation.DesigCode) to foreign key of related table(Personnel).
Database Management System For Private Circulation only

7. See the fileds involving Relationship, DesigCode and Designation.

8. Check the Enforce Referential Integrity Check box.
9. Check the other two check boxes Cascade Update/Delete Related fields.
10. See the Relationship type: One to Many or One to One etc.
11. Create
12. Save and Close the relationship window.

Data Entry in Tables.

Here Designation table is the Master table and Personnel table is the related tables. In
other words you can add employees on existing designation. So primarily enter all the
available designations in the Designation table.
DesigCode Designation
AD01 Director
AC02 Assistant Professor
AC03 Lecturer
AD04 Deputy Director
AD05 Accounts Officer
AD06 Section Officer
AC07 Research Assistant
AD08 Assistant
AD09 Confidential Assistant
AD10 Typist
AD11 Driver
AD12 Gardener
AD13 Roneo Operator
AD14 Peon
Database Management System For Private Circulation only

AD15 Sweeper
AD16 Public Relation Officer
AD17 Security Officer

Enter a few records in the Personnel table. See the sample data tables for data entry.
Remember type the code of designation instead of designation in the designation field.
After entering 10 records save and close the table.
Here entering designation code is a cumbersome process, because you should
remember all designation code. So data entry error may occur. To avoid these problems
build a lookup wizard (Combo box) from designation table. For that perform the following
Select Personnel Table and Design
Select Designation Field
In the filed properties pane select Lookup tab
Display Control: - Combo box
Row Source Type: - Table/Query. (The value of this filed is coming from another table or
query, ie from Designation table)
Row Source: - Click on (…) Button. Don’t Select Table name form the list.
Now select the required table (here Designation)
Designation and click ADD once.
Then close the Show table dialog box. (Rt Click on the filed list pane and choose show
table for the dialog box again)
Drag required fields from field list window to the field row of query builder. Here first
column DesigCode (column 1) and Second Column Designation. (2 Columns)
Close Query builder window and click yes.
Bound column: 1 (Column to be saved. Here type Column number of DesigCode
Column count: - 2
Column Width: 1;2 (1 inch for DesigCode and 2 inches for Designation)
List width: - 3. (Sum of Column width)
Save table. Open it and try to enter data. Now you can see a combo box which will display
the DesigCode and Designation.
Similar technique can be applied for Sex and Caste fileds. Here the answers are
predefined. M or F and SC, ST, OT, OBC, etc. so we can create lookup by giving values,
not from tables.
So redesign personnel table.
Select sex filed and choose lookup tab
Display control: - Combo box
Row Source Type: - Value List (List of values are given by user)
Row Source: - M;F
Bound Column: -1
Column count: 1 and retain all the default values in the rest of property attributes.
Select Caste filed and designs Lookup like this
Display control : Combo box
Row Source Type : Value List
Row Source : SC; ST; OT; OBC
Save the design of your table. Add 20 records in it. Redesign the table for more
meaningful structure as per the guidance.

Modify the above two exercises by using your own ideas. Recreate/create some
databases and design one or two tables in it.

MS Access Exercise III

Create following tables in Payroll database.
Give Proper Validation Rules for Sex and Caste Fields. Give Proper Validation text also.
Database Management System For Private Circulation only

1. Department
Field Data Type Size
DeptCode Text 5 Primary Key
Department Text 30 Initial Capital
2. Designation
Field Data Type Size
DesigCode Text 7 Primary Key
Designation Text 30 Initial Capital
3. Personnel
Field Data Type Size
EmpCode Text 8 Primary Key
EmpName Text 25 Initial Capital

*Designation Text 7 Foreign key

*Department Text 5 Foreign key

Upper case
**Sex Text 1

Upper case
**Caste Text 3

DateBirth Date/Time
DateJoin Date/Time
BasicPay Numeric Integer
4. Salary
Field Data Type Size
*Employee Text 8 Foreign Key
SalDate Date/Time
DA Currency Currency Decimal Place 2
HRA Currency Currency Decimal Place 2
Gross Number Single Format : Currency
PF Currency Currency Decimal Place 2
NET Number Single Format : Currency
Decimal Place 2

For creating a lookup wizard first you select the required field. You can create a
lookup Wizard (Combo box or List box) from a Table, Query or by typing the required
values for the list. First you select the Lookup sheet tab in the Field Properties pane. Then
select a suitable Display control, Say List Box or Combo Box which ever you want. Then
select a Row Source Type, say Table/Query or Value List. If the value of that particular
display control is coming from a table or from a query select Table/Query option. If you
are typing the values select Value List. Here the values of * marked fields comes from
another table. So the Row Source Type of these fields is Table/Query. But that for **
marked fields (Sex & Caste) is given by the user. So select Value list for these fields.
For Value list Row Source cell is filled by the values typed by the user separated by
the semicolumn (;) symbol. For example for Sex Field, Row Source type - ValueList and
Row Source Type – M;F.
For Table/Query click on the … button on the right side of the Row Source cell. Then
Select Suitable table from the Show Table Window and click on the Add button. After
adding suitable table(s) close the Show Table Dialog box. Then Click and Drag Suitable
fields to the Corresponding Column shown below or select the required field name in the
column by using the drop down arrow in the right of each column in the Field row. After
dragging the required fields Close the Query builder window by clickng X mark and click
Database Management System For Private Circulation only

Yes for saving the structure. Note the column count and the no of column in which the
code field lays.
Bound column is the number of code column in the builder window. If it lay in the
First column bound column is 1. That column is going to save in to the hard disk.
Column count is the count of columns in the list. If you have 1 column it is 1 if you
have 2 columns it is 2.
Suppose you want to display the sex field as Male/Female and want to save M/F in
the hard disk. For that you type M;Male;F;Female in the Row source and type bound
column 1, Column count 2. Now the list appears as two columns like

M Male
F Female

Suppose if you don’t want to display the first column select the column widths cell
and type 0;2. that means we are not providing width for first column.
Limit to list –Yes- means user can’t type new values in a combo box. No- means user
can type new values.

After creating the structure of these tables set proper relationships.

Rt Click and choose Show tables. Add additional tables and create the following
relationships properly.

Tick the checkboxes of referential integrity and create the relationship

Then type 5 Departments, 10 Designations, 20 Employees and add some Employee
codes and Date only in the Salary table

EmpCode Department
ADMN Administration
ACF Accounts and Finance
HMAF Home Affairs
EDT Education and Training
SW Social Welfare
ES Economics and Statistics
BD Backward Development
FCS Food and Civil Supplies
IGW Irrigation and Ground Water
AGR Agriculture
AHV Animal Husbandry and Veterinary
TSM Tourism
ELC Electricity
RVN Revenue
PW Public Works
Database Management System For Private Circulation only

Add the following codes to the previous data

Personnel Salary (EmpCode and SalDate only)

EmpCode Desig Dept Employee
Employee SalDate
E01 AD06 ADMN E01 31/12/05
E02 AD08 ACF
E03 AC02 EDT E02 31/12/05
E04 AD12 HMAF E03 31/12/05
E05 AD10 TSM E04 31/12/05
E06 AD08 ACF
E07 AC02 EDT E10 31/12/05
E08 AD11 HMAF E11 31/12/05
E09 AD06 ACF E12 31/12/05
E10 AC02 EDT
E11 AD13 ES
E13 31/12/05
E12 AD12 HMAF E20 31/12/05
E13 AD14 ADMN E21 31/12/05
E14 AD14 EDT
E22 31/12/05
E15 AD14 ACF
E16 AD14 AHV E23 31/12/05
E17 AD13 ADMN E24 31/12/05
E18 AD06 ELC
E30 31/12/05
E20 AD10 ACF E01 31/01/06
E21 AD09 ACF E03 31/01/06
E22 AD09 ADMN E20 31/01/06
E23 AD01 EDT
E24 AC03 EDT E01 28/02/06
E25 AD04 SW E20 28/02/06
E27 AC03 EDT
E28 AC03 EDT
E29 AD05 ACF
E30 AC07 EDT

MS Access Exercises 4 – Queries

Select Queries

It is used to extract records from the tables, which satisfies certain conditions. Select the
Query Sheet tab and click New button in the database window. From the New query
window choose Design view option and click ok button. From the Show table window add
required table(s). Eg. Add Personnel and Designation from the small window and close
the show table dialog box. Then select the required fields from the corresponding tables
and drag them to the field row of column 1, column 2 and so on.
For example drag fields EmpCode, Designation from Personnel table and field
Designation from Designation table. After Dragging/Selecting all required fields from the
field list windows save the query and close it. Then select your query name and click the
open button. Now you can extract the corresponding fields with all data from your table.
Now if you want to filter all employees belongs to a particular designation then
build a query as in the above case. After dragging all required fields to the corresponding
columns. Then select the criteria row of the Designation field from Designation table.
Don’t select the Designation field of Personnel table because the designation field in the
Personnel table contains the Designation code, even though it displays the designation.
(We save the code). Now type the designation such as Clerk in the concerned column of
the criteria row. You can use wild card symbols such as Like “A*” “A*” for all designation
starting with A.
Field EmpCode Name Designation
Table Personnel Personnel Designation
Criteria Like “A*”
or “Vijayan D”
In the above figure you can see a part of the query builder which filters all records
from Personnel table with designation starting with A and or employees having Name
Vijayan D.
That simply means if you want an OR combination you must type the criteria in
each column in different rows. If you want an AND combination you type it in the same
row of criteria.
Parameter Query
In the above if you want to change the conditions/criteria then you must re design
the query. This is not practical. So you can use parameter query. That means in the
Criteria row you can type parameters in square brackets ([ ]). For example if you want to
filter all employees having basic in between 8000 and 15000 then you can design a query
by selecting required fields including Basic. Then in the criteria row of basic column type
Between 8000 and 15000.
15000 It will filter all records satisfying the condition. Instead of giving
the lower limit value (8000) and upper limit value (15000) you can use parameters as
Between [Enter Lower limit Value?] And [Enter Upper limit Value?]. While you are
opening/Running the Query you will be asked by the query for the Lower and Upper lint of
values. Thus you can create a general-purpose query. You can use Mathematical
operators like >, <, >=, <=, <> (Not equal to) SQL statements etc. in the query. The
following query extracts the details of employee who owes the maximum basic pay. Note
the SQL statement in the criteria is in parenthesis.

Field EmpCode Name Designation Basic

Table Personnel Personnel Designation Personnel
Criteria (Select max (basic)
from Personnel)

You can use >=8000 and <=15000 instead of Between 8000 and 15000.
Use # symbol before and after the date. Eg #01/01/2002#
Between #01/01/2001# And #31/12/2001#
Database Management System For Private Circulation only

Between [Enter First Date] And [Enter Second Date] ⇒ Avoid # Symbol here.
Update Query
Update query is used to modify data in a table. So its effect is in the table. You
can’t view any biases if the corresponding messages are switched off. Suppose if you
want to calculate DA, HRA etc in the salary table create a query and add Personnel and
Salary tables in it. The drag DA, HRA, Gross, PF and NET fields to the builder. (Choose
only derived fields in the salary table).
Then click on the Query menu in the menu bar and select Update query from the
pull down list. Then select the Update to row of the DA column. Assume DA is 64% for all
employees. Then Rt. Click on the cell and choose Build option from the popup menu.
From the Expression Builder window Db. Click on the Table object. Select the required
table(s) respectively for building the expression.
First you select the Personnel table and Db. Click on the Basic field appeared on
the right listbox. Now it is transferred to the builder region. Type * mark and 0.64 for DA
Field. Ie now you got an expression like this [Personnel
rsonnel]![Basic] * 0.64
0.64 in the builder. Click
OK button.
Now select HRA update to cell and build the Expression as follows
Personnel]![Basic]>10000,750,500)) for
basic greater than 20000 hra =1000 for basic between 10001 to 20000 hra =750 and 500
for others.
Gross is [Personnel]![Basic]
Personnel]![Basic] + [Salary]![DA] + [Salary]![HRA].
[Salary]![HRA] Here select fields
carefully from two tables. PF is [Personnel]![Basic]
Personnel]![Basic] * 0.0833 and Net is [Salary]![Gross] -
Save the query and close the builder window. Then open the query, read the
warnings and click Yes if necessary. Then open the table sheet tab and open the Salary
table. if all the fields are not calculated once again open the Query and again note the
table. Continue until all the fields in your table are calculated.
Make-Table Query
Create a new query and add Personnel details table. Select required fields from
the field list window. Here you select all fields. Then take the Query ⇒ Make-Table Query
from the menu bar. Now a dialog box for table name is shown. Give a new table name
(say Personnel tab2)
tab2 and select current database radio button for creating the table with
in the current database (Payroll). (You can choose Another database radio button and
type the full database name including path in the text box provided). Click OK button save
and close the query. Then select the query and open it. After that open the table sheet
and check whether the new table is there. Open the table and delete all records.
Then retype some other records in the newly created table for studying how to
append two tables by using Append Query.
Append query
Create a new query and add the newly created table Personnel tab2 and choose
all the fields in it. Then click Query ⇒ Append Query from menu bar. Then select
Personnel table from the combo box for appending to that table. Then select Current
database button and click ok. Check the Append to field names and the Field row field
names are compatible. If it is ok save and close the query. Then run it. Open the
Personnel table for seeing additional records.
You can use criteria for all the above queries.
Delete Query
Before creating the query select the table sheet and take the design view of
Personnel table. Add one more field. Field Name: Retired, Data Type Yes/No. Then save
Database Management System For Private Circulation only

and take the datasheet view put check mark in some records in the retired fields for
indicating that they are retired from service.
Now come back to query. Add Personnel table and select Retired field to the field.
Then click Query⇒ Delete Query. Then give criteria for that field is Yes. Now save and
close the query. Open it. You are going to delete all records of retired people from
Personnel table.
Crosstab Query
Suppose you want the caste wise designation wise list of employees for finding
the number of employees in each caste in each designation. For that you can create a
Crosstab Query. For that select the query sheet and click new button. From the New
Query dialogbox select Crosstab Query Wizard option and click ok. From the Crosstab
Query Wizard window select Personnel table and click Next > button. Now select the
Designation field from the Available fields listbox after that click > symbol for selecting
that field into the Selected fields listbox. (You can add maximum 3 fields in this way. Use
< to deselect the selected field). Againn click Next > and choose Caste field. Then note
the preview shown. If you are satisfied click Next > again and select a suitable function
from the Functions listbox. Here choose count. Select a field suitable for the action of the
selected function. Here select EmpCode and click Next > again. Give a Query name (say
Desig Caste list qry ). And click Finish. Then Close the query and take the design view
then observe the design of the query.
Join Properties
Properties & Duplicates Query
While you are entering data in salary table take care to omit two or three records.
That means don’t enter all the employee code available in the combo box. Then try to
solve this question. Find all employees who didn’t receive their salary?
For that you add Personnel, Designation, Salary tables. Select fields Employee
from Salary table, Name from Personnel table, Designation from Designation Table, Basic
from Personnel table, Date, DA, HRA, Gross, PF, NET from Salary table. Save and run
the query. But this is not your answer.
Now you want to filter Employees records, which are available in Personnel table
and not available in Salary table. In ordinary case you cannot filter these records. For that
you must edit the relation ships. For this you Rt. Click on the relation line in the Query
Builder window pan. If you are properly clicked you get a popup menu having
Join Properties and Delete options. (If you get another one press Esc key/click out side
the menu and again Rt. Click on the line till you get the menu). From the two menu items
select Join Properties option.

From the Join Properties window select the 2nd radio button - ie. “Include all
records from ‘Personnel’ and only those records from ‘Salary’ where the joined fields are
equal” - and click OK button. Save the query again and open/Run it. Now you got the
details of all employees in both tables. Here the Employee code of certain employees
contains null value. That means they didn’t accept their salary yet. Now filter these
records. For that use the following criteria.

Field Emplo Name Designation Basic DA NET

Table Salary Personnel Designation Personnel Salary Salary

Criteria Is Null

Again save and Run the query.

Database Management System For Private Circulation only

Suppose you want to select Records, which come in the table more than once.
Eg.- List all Suppliers who supply more than one parts. Here add one more employee
code such that the employee receives salary more than once (Salary of two months). For
finding this we must include at least three tables as above (Personnel, Designation,
Select Query sheet and click New button. Take design view drag all fields as
shown in the above table. Here there are no criteria. Save the Query and give a name
Duplicates Query.
Query Close the query.
Now again click New button in query sheet. Now select Find Duplicates Query
Wizard and Ok button. Then from the Find Duplicates Query Wizard window select the
Queries radio button and select Duplicates Query from the list of Queries shown in the list
box. Click Next > button. Select the Employee field from the Available fields listbox (Since
it is the duplicating field) and click > to add it in the Duplicate-value fields list. Then click
Next > again. Now you want to select all other available fields. For that click on the >>
symbol. Click Next > again. Give a suitable name and Finish it. Take the design view and
note the SQL.
Similarly you can use unmatched Query wizard.

Query Totals (grouped by clause)


For extracting the department wise designation wise count of employees (count of
employees in each designation in each department) design the following query.
Query⇒New⇒Design view⇒Ok.
Add required table(s), Personnel, and close the show table dialogbox.
Drag required fields (having grouping facility) Department, Designation and EmpCode.
(Count of EmpCode of each desination in each Department.)
Department Rt Click on Query builder
pane and choose Totals ( ∑ at toolbar). Seelct function, Count, Sum, Avg etc as shown in
the figure. Save and Execute query.

Similarly you can extract sum of basic pays of each designation by designining the query
as shown in the figure 10.
Database Management System For Private Circulation only

Derived fields
For calculating Age, Pension year and month, years of service etc we can create derived
fields. Select required fields in the design view of the query. DateBirth, DateJoin fields
should be selected. Rt Click on an empty field cell and select build. Then type a label then
a colon and type the formula or function properly.
Eg: - Age: Round((Date()-[DateBirth])/365,0) and click ok.
or EmpAge:DateDiff(“YYYY”,[DateBirth],Date())
PensionYear:: IIF(Day([DATEBIRTH])=1 And Month([DATEBIRTH])=1, "12/" &
IIF(Day([DATEBIRTH])=1,Month([DATEBIRTH])-1 & "/" &
Year([DATEBIRTH])+55, Month([DATEBIRTH]) & "/" & Year([DATEBIRTH])+55))

SQL Statements.
We can design query by writing SQL statements. For extracting EmpCode, EmpName,
BasicPay from personnel table we can write the following SQL statement.
Query⇒New⇒Design View⇒OK
Close show table dialogbox with out adding table
View⇒SQL View
Type the following

SQL statements.
EmpCode, EmpName, BasicPay FROM Personnel;
SELECT Personnel.EmpCode,
Personnel. Personnel.EmpName,
Personnel. Personnel.BasicPay
Personnel. FROM
For extracting all fields from Personnel table we can use * mark in the select clause.
SELECT** FROM Personnel;;
You can use function in select clause.
Select Max (BasicPay) from Personnel;
Select Min (BasicPay) from Personnel;
Select * from Personnel where BasicPay>=8000;
Database Management System For Private Circulation only

Select * from Personnel where

BasicPay=(Select Max (BasicPay) from Personnel);
P. P.EmpName
P. as EmployeeName,
EmployeeName P.BasicPay
P. FROM Personnel AS P;
Delete Queries
SQL statement for deleting records from the salary table whose basicpay from Personnel
table less than 1000.
DELETE Salary.* FROM Personnel INNER JOIN Salary ON Personnel.EmpCode =
Salary.Employee WHERE (((Personnel.BasicPay)<1000));
Delete records from personnel table whose NET from Salary table <1000.
Delete Personnel.* from personnel where empcode in (Select employee from salary where


You can join results from more than one query having same fields in to a single query by
union statement. For example you can display records of maximum basic pay and
minimum basic pay in a single query. The SQL statements can be constructed as follows.
Query⇒New⇒Design View⇒OK
Close show table dialogbox with out adding table
View⇒SQL View
Type the following SQL statements.
SELECT Personnel.EmpCode, Personnel.EmpName, Personnel.BasicPay,
Personnel.Designation, Personnel.Department
Personnel.Department FROM Personnel WHERE
(((Personnel.BasicPay)=(Select Max(basicPay) from personnel)))
SELECT Personnel.EmpCode, Personnel.EmpName, Personnel.BasicPay,
Personnel.Designation, Personnel.Department FROM Personnel WHERE
(((Personnel.BasicPay)=(Select Min(basicPay) from personnel)));


DateDiff(“M”,[DateBirth],Date()) ⇒Difference of two dates in months.

DateDiff(“d”,[DateBirth],Date()) ⇒Difference of two dates in number of days.
DateAdd(“yyyy”,55,[DateBirth]) ⇒Add 55 years to date of birth
DateAdd(“M”,8,[DateBirth]) ⇒Add 8 months to date of birth

CVDATE ⇒ Age as on 1/1/2006.
CVDate ⇒ Convert a date string to date value.
DAY(CVDATE(“15/08/1947”) ⇒ 15
MONTH(CVDATE(“15/08/1947”) ⇒ 08 for August
YEAR(CVDATE(“15/08/1947”) ⇒1947

Eg: - IIF([BasicPay]>=8000,400,250) ⇒formula for HRA, etc

Try to solve the following Questions.

1. Find all employee details whose basic greater than 10000?

2. List all employee details whose basic is in between 8000 and 15000 (use Between)?
3. Redesign the above query by using >=, <= operators?
4. List details of all peons?
5. Display details of Assistants having basic greater than 6800?
6. Extract details of all Peons along with Drivers?
7. Extract details of the employee having maximum basic?
8. Display details of employee with minimum Basic?
9. Display all employees who are not yet received their salary?
Database Management System For Private Circulation only

10. Display all employees whose service is greater than 20 years?

11. Display all employees who have only two more years of service?
12. Display the Age of all employees along with their Date of Birth?
13. Display the Years of service, moth and year of pension of employees having age
greater than or equal to 45?
14. Display details of Assistants & Confidential Assistants whose service greater than 5
15. Select Employees having either service greater than 10 years or designation is
Director or basic is greater than 10000?
16. Create Query by using criteria in the name field and note the differences. Like
“Rm*”, Like “*ni”, Like “????”, Like “?amu”, Like “D??u”?
17. Display Employee code, Name, Designation, Department and basic of all
18. Filter all employees whose record comes more than once in salary table?
19. Find how many designations are vacant in the Personnel tables?
20. Find the Departments in which no employees are associated?
21. Create a union query to display the maximum basic pay and minimum basic pay
with in a single query?
Forms are used to enter data into the tables. It is a front-end tool. The end users are
interacting with the database by the help of forms only. You can create forms from table,
select queries and parameter queries. Here we want to create 4 forms. One for
Department table, one for Designation, another one for Personnel and one for Salary.
For creating forms select Forms sheet tab and click New button. First select the Form
Wizard option. Then select a table/Query name from the combo box: - Choose the table
or query where the object’s data comes from: - shown below the dialog box. Then click ok.
If you are using wizards option you have a facility to select table/query names from the
Table/Queries combo box shown above the available fields - list box.
For example if you want to create a form for Personnel table follow the following steps.
1. Select Forms Sheet tab, click New button, select Form wizard option and click OK – or
- db. click on the Create form by using wizard option in the window.
2. From the Tables/Queries combo box, select the Personnel table or the table you
required for creating the form.
3. Now in the Available Fields listbox contains all the fields in the selected table.
4. Select the required field from the list box and click on the > button to transfer the
selected field to Selected Fields listbox.
Hint: - Don’t select Derived fields such as DA, PF etc for data entry forms.
You can use >> button for transferring all the available fields to the selected fields
listbox. Also use < to remove a single field from the selected fields list and << for
removing all fields simultaneously.
5. Click Next > button.
6. Select a layout from the available options. Say Columnar by clicking on the radio
button. Hint: - Columnar is suitable for data entry forms. Tabular/Datasheet is
suitable for view forms for viewing all records at a time.
7. Click Next > button.
8. Select a style from the available options. Say Standard. Hint: - Forms must legible
rather than beauty.
9. Click Next > button.
Database Management System For Private Circulation only

10. Give a name for your Form say Personnel Data Entry Form. And click Finish
Suppose you want to create a form by using more than on table either you create a
select query by using them and create a form by using that query - or - by using form
wizard option after completing step 4 again select another table by repeating from
steps 2 to 4.
Designing Forms.
You can design forms by following the steps given below.
1. Select Forms Sheet tab, click New button, select Design View option. Then select the
table/Query name in the combo box “Choose the table or query where the object’s
data comes from:” and click OK – or - db. click on the Create form in Design view
option in the window.
2. If you are not selected a table/query name as data source the take the properties of
form. For that rt. click on the left top corner of the form’s ruler line and select
properties option. Note the title bar of the newly appeared window must be Form.
3. Select the Data sheet of the properties tab control and select the require table/query
name from the Record Source combo box. Just note all other options of the sheet
4. Close the properties dialog box. Then note a field list is appeared in a small window.
If it is absent click view menu and select Field List option.
5. Adjust the length and breadth of the designer sheet. For that drag from the border of
the sheet.
6. Drag the required fields from the field list window to the design window.
7. Now you got a label (transparent one) and a text box (white coloured sunken one)
containing the field name.
8. If you want to move the controls, select suitable control by clicking on it. Then bring
the mouse pointer above border of the control. Now you got a stretched palm symbol.
Click and drag the control to a suitable position. Note that the text box as well as the
Label moves together.
9. If you want to move any one of the control to move a certain position bring the mouse
pointer to the small black square on the right top corner of the required control. Now
the mouse pointer becomes a pointing palm. Then click and drag the control.
10. Then design your form by using your commonsense, imagination power and beauty
11. Save and give a name. Close the design view. Open the form and add records.
Adding additional controls in your forms
Add Command buttons.
1. From the Toolbox select the command button icon and draw it in your form gently.
2. If the builder wizard (second icon in toolbox) is on you get a “Command Button
Wizard”. From the categories list select any one category. Say Form operations.
3. From the actions list select an action. Say Open form. Then click Next > button.
4. Select the required choice. Here select a form name. (Say “Designation Data Entry
From”). Then click Next > again
5. Here select a radio button say Open form and show all records. Click next>.
a. If you are selecting “Open form and specific data to display” and click Next >
b. Then select a field from first form and select a link field from the second one.
Database Management System For Private Circulation only

c. Click < > to create a link. Then click Next> and follow the steps.
6. Select Text radio button and type - Enter Designation – and click Next again.
7. Give a name for your command button control. Say OpnFrmCmdBtn.
8. Then click Finish, save and view the form.
9. Click on the button and note the actions.
Adding text box to show total values.
If you want to show the DA, Total in text boxes in Personnel data entry form in read
only/locked mode follow the instructions.
1. Select the Personnel data entry form in design view.
2. Adjust the length and breadth of the forms so that it can accommodate two or three
3. Then select the textbox tool from the toolbox and draw a textbox at the suitable
position in the form.
4. Now click on the label having caption Text no: and type a caption say DA:
5. Then click on the unbound textbox and simply type =[basic]*0.32
6. Similarly you can add textboxes to your form and display results in it.
Note: - These results are derived from the basic pay. So user need not enter the values.
So for avoiding data entry mistakes lock/disable these fields.
7. For locking these fields select all fields by using mouse/shift key and rt. click on it
select the properties option and took Data sheet tab. Chose Enabled: No, Locked:
8. Now save the form and open it. See the changes.
Adding events in Forms/controls
You can perform a particular set of actions when an event occurs. Examples for events
are form load event, form unload event, mouse click event, keydown event, mouse move
event etc.
Suppose if you want to calculate DA, HRA, Gross, PF, NET fields in the Salary form
whenever you enter/modify the Basic pay. For that first create a query including
Personnel, Designation and Salary tables. Add fields Employee from Salary table, Name
from Personnel table, Designation from Designation table, basic from Personnel table,
Date, DA, HRA, Gross, PF and NET from Salary table. Save the query, give name
Salary from creation query.
Now create a form in design view by taking Salary from creation query as its data source.
And arrange the fields as shown in figure in next page. In that form select textboxes DA,
HRA, Gross, PF and NET, Rt. click on any one of them. Select properties option, choose
Data Sheet and change Enabled to No.
Now save the form and give name Salary Data Entry Form. Now you want to calculate
DA, HRA etc and wants save the values to the Salary table. That means whenever the
user entered/change the basic all those fields must be calculated. For that follow the
instructions given.
Database Management System For Private Circulation only

1. Rt click on the basic text box and select the properties from the popup menu.
2. Select the Event sheet tab.
3. Select the after update event and click the builder button …
4. Select Macro Builder from the Choose builder dialog box. Give a name for your
macro – say Salary Calculation Macro.
5. Select Setvalue in the first row of the Action column.
6. Press tab key in the keyboard. Now press F6 function key or click on the Action
Arguments pan of the window
7. Select Item row and click on the builder button.
8. Then db click on the Forms option, db click on the Loaded forms and select the
form name. Now the <Form><field list> is appeared on the middle list box.
9. Now db click on the field name, which you want to set in the item. Here we want to
set DA.
Hint: - You can simply type the field name in square bracket in the Item row as shown
Item [DA]
10. Then build the Expression as in the above case.
Item Forms![Salary data entry form]![Basic] * 0.64
or simply type
Item [Basic] * 0.32
11. Then select the second row of the Action column and again select setvalue and press
tab key.
12. Again select the item cell and build ⇒Forms![Salary data entry form]![HRA] in the cell
for setting HRA filed.
13. Then build the Expression as ⇒ iif(Forms![Salary data entry form]![Basic] >=
15000,1000,iif( Forms![Salary data entry form]![Basic] >=1000,750,500))
14. Similarly set actions, item and expressions for Gross, PF and Net filed.
15. Save and close the macro.
16. Close the properties dialog box, save and open the form.
17. Type some records and see the changes after you typing the basic pay.
Database Management System For Private Circulation only

18. After entering two or three records close the form and open the Salary table for seeing
the changes.
Q. Create a view form for seeing EmpCode, Name, Department, Designation, Dateofjoin,
Dateofbirth, Age, Service, Sex, Caste and Basic.
Here you must note that you are going to create a view form. That is now data
entry/Editing is needed. It is better to see more than one record at a time for certain
comparisons. So create a tabular form by using a query, which is created from
Personnel, Designation and Department tables OR you must design the form by using
Form Wizard and select fields from the required tables. Give a name Employee details
view form.
Then take the design view of your form and select all bounded/unbounded controls except
labels and take the properties of them. Select the Data sheet tab and change the Locked
property to Yes. Now you cannot type/change the values in the text controls.
Q. Create an unbounded form and add some command buttons for opening another
forms and running queries etc.
The form must be as shown bellow.

The first two buttons are used for opening other forms, which we have discussed earlier.

Private Sub CmdSalCalQryBtn_Click()

On Error GoTo
Dim stDocName As String
stDocName = "Sal Cal Qry"
DoCmd.OpenQuery stDocName,
acNormal, acEdit
Exit Sub
MsgBox Err.Description
Resume Exit_CmdSalCalQryBtn_Click
End Sub
For opening a query (update query) you must select miscellaneous option from the
command button wizard select Run Query from the Actions listbox. Click Next > and
Database Management System For Private Circulation only

choose text or picture radio button whichever you like. Click next > and give a button
name and click Finish.
After saving the form select the properties of a command button (Design View) and then
select the Event sheet tab and click on the on click [event procedure] builder button. Now
you can see the VBA coding there. A sample coding for run a query is shown as below.
If you want to add option button group in the Sex field first change the data type of your
Sex filed in the Personnel table. Field name: - Sex, Data type: - Number, Field Size: -
Byte. Then change Male as 1 and Female as 2. Change the display control in the lookup
sheet tab as text box.
Come back to forms sheet and take the design view of Employee form. Remove sex
combo box from it and select the Option Group frame from the toolbox. Type Male as first
value and Female in the Second Row. Then follow the instructions given by the Wizard.
Suppose you want to store the passport size photograph and remarks of employees first
take the table sheet tab and take design view of the “Personnel” table. Add one more field
“Photo”; Data type “OLE Object”. Then add one more field “Remarks”, Type “Hyperlink”.
Save and close the table design view.
Open the forms sheet tab and create a new form (Columnar) from Personnel table. After
finishing the form give a name “Employee New Form”. Then take the design view of you
1. Select the Photo frame and adjust the size of that frame to that of a passport size. (For
that bring the mouse pointer to the bottom right corner of the frame. When it becomes
a double-ended arrow drag for a suitable size.)
2. Arrange all the fields in a beautiful manner.
3. Save and close the form’s design view.
4. Select the Form view /Open the form.
5. Rt. click on the Photo Frame and choose Insert object.
6. If you have a scanned photo of the employee select the create from file option and
click the browse button and select the filename and click ok
7. Here you have no such photos. For studying we select create new radio button and
choose Microsoft Clip Gallery and click ok.
a) Select a suitable picture from the clipart and insert it.
8. Now you can see only a portion of the picture in the frame. Fro adjusting the picture
with in the frame’s limit take the design view of the form
9. Then take the properties of the frame and select the Format sheet tab.
10. Change the Size Mode to Stretch option.
11. Save and close the design view.
12. Open the form and check the new view.
13. For adding a hyperlink rt. click on the remarks field and choose Hyperlink⇒Edit
Hyperlink… option
14. Add text in the “Text to display” text box.
15. If you want to display a screen tip on the field click on the screen tip button.
16. Select a file name by clicking on the File button and click ok

Sub Form
For seeing all the employees in a department along with department details and
employee details we can use these type of forms.
a) Consider the logic for this. One department contains more than one employee. So
take a Columnar view for Department form and a Tabular view for Employee details.
b) First create a columnar form from Department table. Say “Department master form”
c) Then create a tabular form from Employee details. Say “Employee Sub Form”
d) Now take the design view of the columnar form “Department master form”.
e) Maximize the window and adjust the width and height of the form (to a full screen).
Database Management System For Private Circulation only

f) Then select the Sub form/ Sub report tool from the tool box and choose the Use an
existing form and select the tabular form “Employee Sub Form” and click Next>.
g) Select a suitable link field from the options given. Here the deptcode filed from
Department table and Department field form Employee field is the linking fields. So
here we select “Show Employee for each record in Department using Deptcode.
h) You can use “Define my own” radio button and select the link fields from the combo
boxes (If there is more than one link fields you can use this option)
i) Click Next> and click finish button.
j) Now take the form view of the master form
k) Now you can see two data controls. Outer one is used to navigate through Master
form (Department) and inner one is for navigating through Employee details (Tabular
For better performance take the Design view of tabular form and arrange the fields
suitably in a single row.
Question -
1. List all employees based on their designation?
2. Display a caste wise list of the employees
Discuss the steps for displaying the sex-wise list of employees.
Here sex is a field in the Personnel table. So create two forms one Columnar and one
Tabular from the same table Personnel.
Columnar form contains the Sex filed only. (Create form by using Form wizard option).
Then select all other required fields from the same table and create a tabular form.
Design the columnar form and drag the Sub form in it. Then choose the “Define my own”
radio button and select the link field Sex from the two combo boxes Form/Report fields
and Sub form/Sub report fields. Then finish, save and took the form view.
Pass form fields as query parameter.
Suppose if you want to filter employee details whose name is typed in a text box in a form.
First select forms sheet and click new and select design view. (Do not select table name).
Draw a text box and take the properties. Select other sheet tab and give a name for your
text box, say Fnametxt. Close & Save the form. Now select the query tab and design a
query from the Personnel table. Build the criteria for name is Like
>]![ ].
Again come back to forms sheet and take the design view of the form. Add a command
button and select the Miscellaneous Category and select Action as Run Query. Select
your Query name from the list; give name for your button and save the form. Then open
the form and type a name in the text box. See the action.
Search Forms Used to pass parameters of query
1. Forms⇔New⇔Design view⇔Ok
2. Add required text boxes from tool box (ab| ab|)
3. Save Form 'FrmSearchXXXX'
4. Rt. Click on textbox/Display Control ⇔Properties
5. Other⇔Name⇔Type Control Name. 'TxtEmpName'
6. Close Properties window and save
7. Close Forcm
8. Query⇔New⇔Design View⇔Ok
9. Add required table/tables. 'PersonnelDetails'
10. Drag required fileds
11. Rt. Click on criteria cell of required filed and choose build
12. Type require options (Like, Between etc)
13. Double click on 'Forms' object, double click on 'All Forms' object and choose required
form name
14. Select require control name and paste
Database Management System For Private Circulation only

15. Close builder and save query. 'QryBasicFilter' etc.

16. Close query
17. Forms⇔New⇔Auto form Tabular⇔select query name 'QryBasicFilter'⇔Ok
18. Click Ok to bypass the parameter and Save Form. 'FrmSearchResult' etc
19. Close form and select 'FrmSearchXXXX' ⇔Design
20. Add a button from tool box
21. Select Form operations⇔Open Form⇔Next
22. Choose form name from the list 'FrmSearchResult'⇔Next
23. Choose Text option and Type 'Search' etc
24. Next ⇔ and type a button Name 'BtnSearch'
25. Finish, save and run the form

Creating forms forfor salary calculation

1. Query⇔New⇔Design View⇔Ok
2. Add PersonnelDetail and Salary Tables
3. Select 'Employee' Field (Foreign Key) from 'Salary', 'EmpName', 'BasicPay' from
'PersonnelDetails', 'SalDate', 'DA', 'HRA', 'Gross', 'PF' and 'NET' from 'Salary' Table
and 'Photo' From 'PersonnelDetails' Table.
4. Save Query as 'SlaryQuery'
5. Close Query
6. Forms⇔New⇔Design View⇔OK
7. Right Click at the top left corner of the form and choose 'Properties' of the form.
8. Data⇔Record Source⇔'SalaryQuery'
9. View⇔Field List
10. Select all fields from field list window. Click on first field name (Employee), hold down
shift key and click on last field name.
11. Drag field names to the centre of the form.
12. Arrange Fields Properly.
13. Save Form and Give a Name Employee EmpName
'SalaryCalculationFrm' SalDate BasicPay
14. Rt Click on SalDate Field
15. Properties
16. Event DA Photo
17. AfterUpdate (...) Clcik HRA Rt Click here
18. Macro Builder Gross and choose
19. Give a Macro Name (SalCalMacro) PF Properties.
20. Action: - SetValue Net Format
21. Item: - [DA]
Size Mode: -
22. Expression: - [BasicPay]*0.64
23. Action: - SetValue
24. Item: - [HRA]
25. Expression: - IIF([BasicPay]>=6000,600,300)
26. Action: - SetValue
27. Item: - [GROSS]
28. Expression: - [BasicPay+[DA]+[HRA]
29. Action: - SetValue
30. Item: - [PF ]
31. Expression: - ([BasicPay]+[DA])*0.0833
32. Action: - SetValue
33. Item: - [NET]
34. Expression: - [GROSS]-[PF]
35. Action: - MSGBOX
36. Message: - 'Calculation Completed'.
37. Save and Close Macro
38. Save form
Database Management System For Private Circulation only

39. Take Form View (View⇔Form View)

40. Try to Add a New Record by giving salary to an existing employee.
Designing Custom Search Forms using VBA Coding
1. Forms⇔New⇔Design View⇔Ok
2. Add a text Box(ab|) from tool box, type Label 'Enter/Select Name to Search:
3. Rt Click Textbox and choose Properties.
4. Other tab⇔Name⇔"TxtEmpName"
5. Add a Combo box from tool box
6. Cancel the builder wizard window
7. Click on Label of Combo box and delete it.
8. Take Properties of Combo box
9. Other⇔Name⇔'CboEmpName'
10. Format⇔Visible⇔No
11. Data⇔Row Source Type⇔Table/Query
12. Row Source⇔(...)⇔Add 'PersonnelDetails' Table⇔Close Show Table dialog
13. Drag EmpName filed ⇔close Query builder window ⇔Yes

14. Add One More button as shown

15. Type Caption as '?'
16. Properties of Button⇔Other⇔Name⇔BtnNameSearchHep
17. Event⇔On Click⇔On Click⇔(...)
18. Code Builder⇔Ok
19. Type the following code inside the Private Sub BtnmpNameSearchHelp_Click() and
End Sub

Private Sub BtnmpNameSearchHelp_Click()

CboEmpName.Visible = True
TxtEmpName.Visible = False
End Sub
20. Then from Object combo box at top left of code window select CboEmpName
21. Now you can see two line like
Private Sub CboEmpName_BeforeUpdate(Cancel As Integer)
|(Place and keep the cursor at this position)
End Sub
22. Now Select Change from the combo box at right of code window
23. Now 2 more lines like Private Sub CboEmpName_Change() and End Sub
24. The type the following code
Private Sub CboEmpName_Change()
Dim strEmpName As String
strEmpName = CboEmpName..Text
TxtEmpName.Visible = True
CboEmpName.Visible = False
TxtEmpName = strEmpName
End Sub
25. Close Visual Basic Code windows and save
26. Now select the two controls TxtEmpName and CboEmpName
27. Format⇔Size⇔Widest
28. Format⇔Size⇔Tallest
29. Take Properties of CboEmpName ⇔Format⇔Visible⇔No
30. Arrange the CboEmpName exactly above the TxtEmpName
Database Management System For Private Circulation only

31. Save and Close Form

32. Query⇔New⇔Design view⇔Add Tables
33. Drag required fields and save the Query 'QryEmpNameSearchResult'
34. Rt. Click on criteria Cell of relevant filed and choose Build
35. Then Select Control name from Forms⇔All
Forms⇔FormName('FrmEmpNameSearch')⇔Select Filed(TxtEmpName)⇔Paste
36. After building Click ok
37. Save and close query
Create a tabular form from 'QryEmpNameSearchResult'
38. Save 'FrmEmpNameSearchResult' and close form
39. Redesign the 'FrmEmpNameSearch' and add one more button as below

40. Open 'FrmEmpNameSearchResult' form by using this button

Practical Exercise on MS Access

Open a New database - InventoryControl

Create a table to store item details of Inventory by using Design View

Define the Field Name, Data Type description and Filed Properties

Name of Field Data Type

ItemCode Text Primary Key (Edit⇒Primary Key)
ItemName Text Name in Capital Letter
Unit Text Kg, Numb, Packet, Bottle
OpeningStock Number Opening stock as entry date
UnitPrice Number Value of one unit
LastUpdate Date/time Last purchase date
ReorderLevel Number Minimum quantity to purchase order
Electronic Yes/No To know whether that is an electronic item
PresentValue Number (Update the field through a Query – multiplying Opening
stock by Unit Price)

Field Properties
Name of Field Field Format Default Validation Required Index
Size Value Rule
ItemCode 5 Yes
ItemName 25 > Yes (Duplicates
Unit 6 Numb Yes
UnitPrice Single
LastUpdate Medium date Date()
ReorderLevel Single 100 Between 100
and 5000
Electronic Yes/No No
PresentValue Double
Database Management System For Private Circulation only

Save the table as ‘ItemTable


Open the table and enter more than 20 rows of data

a) Create a new Table ‘Suppliers’ with the following details
SupplierID Text 10 Primary Key
SupplierName Text 30
ContactPerson Text 20
Address Text 50
Telephone Text 15

b) Create a new table ‘Office’ with the following details

OfficeId Text 5 > Primary Key

OfficeSection Text 25
SectionHead Text 25

c) Create a new table ‘Purchase’ with the following filed details

PurchaseId AutoNumber (Primary Key)
ItemCode Text 5 > (FK from Itemtable)
PurDate Date/Time Short Date
PurQuantity Number Integer
PurPrice Number Single
Supplier Text 10 (FK from Suppliers table)

d) Create a new table ‘Issue’ with the following

following filed details
IssueId Autonumber (Primary Key)
Issuedate Date/Time
Itemcode Text 5 > (FK from Itemtable)
Qunatity Number
Office Text 5 (FK from Office table)

Create relation ships, Add 20 items in itemtable, 8 offices in office table, 10 suppliers in
suppliers table, 10 purchase records and 20 issue records in corresponding tables.

Create a new database ‘Airlines’ and create the following tables. Give proper filed with
and properties.

Company FlightDetails CityDetails

FlightCode(PK) CityCode(PK)
FlightName CityName
CompCode (PK)
CompCode(FK) CityType (Lookup)
CopmanyName Days (Lookup)



Value for Days lookup (Daily;SUN;MON;TUE;WED;THU;FRI;SAT or type a value)

CityType: (Metro; Urban; Semi Urban; Rural) use code to save and display full string
Database Management System For Private Circulation only

Create relationships, Forms and enter data in Company, CityDetails, FlightDetails and

Create a new database ‘College” and create the following tables. Give proper filed with
and properties.
Department WorkDetails
DeptCode ProfName ProfCode(FK)
(PK) ProfAddress Department(FK)
ProfSex (Lookup) TotalHours

Create relationships, Forms and enter data in Department, Professor and WorkDetails.
Create all forms for the above databases.
MS Access Exercise
Now we are going to add two more tables in the table sheet of Payroll database.
 Create a new table with fields {Religioncode (Primary key), text, 1) and Religion, text,
15}. Save tha table and give name “Religion Table”

Caste ReligionCode Religion

Caste Religion
α 1 B Buddhist
Br Bramin H
H Hindu
Ez Ezhava H
M Muslim
Ku Kurava H
X Christian
Lc Latin X
Mr Marthoma X
Na Nair H
Nd Nadar H
Or Orthodox X
Pu Pulaya H
Rc Roman X
Sh Shya M
Su Sunni M
Sy Syrian X
Th Thiya H
Create another table having fields Castecode(Primary key), text, 2), Caste text 20 and
Religion, text, 1 – Lookup Wizard from table “Religion Table”. Save the table and give a
name “Caste table”
Give some Records as above
Now design the Personnel table and select the caste field.
1. Click the Insert⇒Rows menu. Type “Religion” as field name in the newly created row.
Field type Text size 1 (Lookup wizard from table “Religion table”)
2. Redesign the caste field (text, 2, Lookup wizard from “caste table”).
3. Save and open the Personnel table. Delete all the values of caste filed.
4. Close and save the table.
5. Click the Tools⇒Relationships menu.
6. Rt click on the window and select Show tables window.
7. Add Religion table and Caste table.
8. Make proper relation ships as follows.
a. [Rligion table]![R
Religioncode][Caste table]![Religion]
b. [Caste table]![C
Database Management System For Private Circulation only

9. Save and close it.

10. Open the “Personnel” table and select values for Religion and Caste fields
11. Now you can create a Select Query by adding Personnel, Religion table, Caste table.
12. Select Empcode, name, sex, basic from Personnel table, caste from caste table and
religion from religion table.
13. Save the query, give a name and open/Run it.

Here you note that it is very difficult to select a caste for a religion.
Suppose if you want to add the details of an employee. While you are entering the
Religion -say H –filter all the castes which under Hindu Religion
14. First you design a form for Personnel details. Say Employee Master form.
15. Then add a combo box from the toolbox as shown in the form below. Cancel the
builder window (Unbounded).
16. Give a name to your combo box say CstRgnCmbo

17. After that create a parameter query from caste table.

18. Add castecode, caste and religion from the table.
19. In the criteria cell of Religion build the parameter as [Forms]![Employee Master
form]![Religion]. Here we filter the caste based on the value of Religion combo box in
the “Employee Master form” form.
20. Save the query and give a name “Religion Filter qry”.
21. Close it and select the Forms sheet tab
22. Then select the newly added unbounded combo box and take the properties.
23. Choose the data sheet tab and select the following as below
24. Row Source type : Table/Query
25. Row Source : (Build) add Query - Religion Filter qry - to the builder
window, Select CasteCode to First column and Religion to
the second column.
26. Save the builder window.
27. Bound column : 1 (Code column)
28. Then select Format Sheet tab
29. Column count : 2
30. Column widths :
31. Visible : No
32. After that select the religion combo and choose the event sheet.
33. Select On lost focus⇒ select [Event Procedure] from combo box and click … button.
34. Type the following as below.

Private Sub Religion_LostFocus()
CstRgnCmbo.Visible = True
Database Management System For Private Circulation only

CstRgnCmbo.RowSource = "SELECT [Religion Filter qry].[CasteCode],

[Religion Filter qry].[Caste] FROM [Religion Filter qry];"
DoCmd.DoMenuItem acFormBar, acRecordsMenu, 5, , acMenuVer70
End Sub
35. Close the vba window.
36. Again select the CstRgnCmbo combobox again
37. Select properties and choose Event sheet tab.
38. Select the On lost focus event and choose [Event Procedure] and build
Private Sub CstRgnCmbo_LostFocus()
Dim tp As String
tp = CstRgnCmbo.Text
Caste.Text = tp
CstRgnCmbo.Visible = False
End Sub
39. Close the vba window.
40. Now save the form and view the records.
Note: - You can write code in the Change/Lost focus event of “Religion” combo box for
filtering the values in “Caste” combo box directly instead of using suppurate combo box
“CstRgnCmbo”. It can be as follows.

Private Sub Religion_Change()

Dim tp As String
tp = Religion.Text
Caste.RowSource = "SELECT [Caste table].[CasteCode], [Caste
table].[Caste],[caste table].[religion] FROM [Caste table] where [Caste
table].[religion]='" & tp & "';"
DoCmd.DoMenuItem acFormBar, acRecordsMenu, 5, , acMenuVer70
End Sub

Explanation of syntaxes
DoCmd.DoMenuItem menubar, menuname, command[, subcommand][, version]
menubar Use the intrinsic constant acFormBar for the menu bar in Form view.
Menuname You can use one of the following intrinsic constants:
You can use acRecordsMenu only for the Form view menu bar in Microsoft Access
version 2.0 and Microsoft Access 95 databases.
For other menus, use the number of the menu in the Menu Name argument list, as shown
in the Macro window in previous versions of Microsoft Access (count down the list,
starting from 0).

command You can use one of the following intrinsic constants:

acNew, acSaveForm, acSaveFormAs, acSaveRecord, acUndo, acCut,
acCopy, acPaste, acDelete, acSelectRecord, acSelectAllRecords,
acObject, acRefresh
For other commands, use the number of the command in the Command argument list, as
shown in the Macro window in previous versions of Microsoft Access (count down the list,
starting from 0).
subcommand You can use one of the following intrinsic constants:
acObjectVerb, acObjectUpdate
Database Management System For Private Circulation only

The acObjectVerb constant represents the first command on the submenu of the Object
command on the Edit menu. The type of object determines the first command on the
submenu. For example, this command is Edit for a Paintbrush object that can be edited.
version Use the intrinsic constant acMenuVer70 for code written for Microsoft Access
95 databases, the intrinsic constant acMenuVer20 for code written for
Microsoft Access version 2.0 databases

Instead of using the combo box you can use a sub form.
1. Create a columnar form for Personnel table.
2. Create a tabular form for “caste table” table.
3. Design Employee form and draw the sub as follows

4. Caste form is on the right side of the Employee form.

5. When the builder wizard appears select the caste tabular form from the list of
forms. Click Next >.
6. Select Define my own radio button.
7. Choose the Religion field from the form/report combo and the same from the
subform/subreport combo.
8. Click Next> and finish the wizard.
9. After saving you can see the form view.

Parameter query as the back born (Data source) of a form.

1. Create a query from Employee and Designation table as follows.

Field EmpCode Name Designation Basic

Table Personnel Personnel Designation Personnel
Criteria [Enter a Designation? ]

2. Save the query as “Filtr Frm Crtng Qry”

3. Then design a tabular form from the “Filtr Frm Crtng Qry”.
4. Save, give name “Designation
Designation fltr frm”
frm and take the form view.
Instead of using run time parameter you can use a parameter form from which you can
select the designation.
1. For that first design an unbounded form.
2. Add a combo box from the toolbox and rename it as “Desigcbo”.
3. Select the option button “I want the combo box to look up the values in a table or
query.” And click Next>
4. Select the designation table and click Next>
5. Select the designation field from the list and click Next>
6. Note the preview and click Next> again and finish it.
Database Management System For Private Circulation only

7. Save the Form and give a name “Parameter frm”.

8. Add a text box and give name as “txtdpdesig
9. Select the Format sheet tab and change the Back Style : Transparent
10. Change the Special Effect : Flat.
11. Change the Fore color : {select the colour of your form (12632256).} for making the
font invisible
12. Select the combo box again and take the event sheet. And change the On Change
event to [Event Procedure]. Then click the builder button.
13. Type the following code .
Private Sub Desigcbo_Change()
Dim tp As String
tp = Desigcbo.Text
txtdpdesig.Text = tp
End Sub
14. Save and close the form say “Parameter frm”
15. Then redesign the query “Filtr Frm Crtng Qry” as follows

Field EmpCode Name Designation Basic

Table Personnel Personnel Designation Personnel
Criteria Forms![Parameter frm]![txtdpdesig]

16. Then select the form Parameter frm and add command button on it.
17. Choose Form operations from the categories and select Open form from the actions
list respectively
18. Click next and choose the “Designation fltr frm” and follow the instructions.
19. Save the “Parameter frm” and open it.
20. Select a designation from the combo box.
21. While we are changing/selecting a designation in the combo box it is transferred to
the Textbox. But we can’t notice it owing to the same colour of text and form.
22. When you click the command button it will open the form Designation fltr frm. But the
form is derived from the parameter query Filtr Frm Crtng Qry. It requires a parameter
designation, which comes from the (Parameter frm)’s textbox.

MS Access Exercise 7

Select the module sheet tab and create a new module. Type the following code in it.

Option Compare Database

Public Function SalCals(ByRef Basic As Integer, ByRef per As Single, ByRef rtn As
Single) As Single
‘MsgBox Basic & vbCrLf & per ‘for checking values
rtn = Basic * per
‘MsgBox rtn ‘for checking result
End Function

Save the module and give name as “SalCal”

Then open the form sheet tab and create a form as shown below from Personnel table.
Database Management System For Private Circulation only

Here we add two textboxes named “DATXT” and “PFTXT” respectively.

Then add one more Command button named “CalBtn”, caption Calc.
Select the click event of the button choose the [Event procedure], and type the following

Option Compare Database

Public rtn As Single
Private Sub CalBtn_Click()
Call SalCal.SalCals([Basic], 0.33, rtn)
DAtxt.Text = rtn
Call SalCal.SalCals([Basic], 0.0833, rtn)
PFtxt.Text = rtn

End Sub
Save and run the form. Click on the button for seeing the result.
Similarly you can use modules for calling sub procedures/Functions.

More VBA Coding sample

Dim db As New ADODB.Connection

Dim rs As New ADODB.Recordset
Private Sub Command26_Click()
On Error GoTo Err_Val
Dim sSQL As String
Dim txtval As String
txtval = txttest.Text
'For extracting a details
'for string
sSQL = "Select * from Personnel where Personnel.empcode='" & txtval & "'"
'for numeric field
'sSQL = "Select * from Personnel where Personnel.basic=" & iVal
'for date value
'sSQL = "Select * from Personnel where Personnel.dateofbirth=#" & dateVal & "#"

db.Provider = "Microsoft.jet.oledb.4.0"
db.Open "C:\My Documents\payroll.mdb", admin
'rs.Open ""Personnel
Personnel", db, adOpenKeyset, adLockOptimistic
rs.Open sSQL, db, adOpenKeyset, adLockOptimistic
Do While Not rs.EOF
MsgBox rs.Fields(0) ' Set this value to a filed/textbox in to your form
Database Management System For Private Circulation only

Exit Sub
If db.State = adStateOpen Then
End if
'Type Proper error messages.
End Sub
Dim txtval1 As Date, txtval2 As Date
txtval1 = CVDate(txtDate1.Text)
txtval2 = CVDate(TXTDate2.Text)
sSQL = “Select Empcode,Name,Basic from Personnel”
sSQL = "Select * from Personnel where Personnel.DateofBirth
Personnel.DateofBirth between #" & txtval1 & "#
and #" & txtval2 & "#"
sSQL =”Select Salary.Personnel,
Salary. , Personnel.
,Salary. from
Personnel,Salary where Personnel.Basic
Personnel.Basic >= " & iVal

Calulating DA, PF etc by using code.

Add a command button named “CmdBtnCalc
CmdBtnCalc in your form and write the following code in
the click event of it.
Private Sub CmdBtnCalc_Click()
Dim iBasic As Integer
Dim varVal As Variant
iBasic = Val([Basic].Text)
If iBasic >= 10000 Then
varVal = iBasic * (32 / 100)
ElseIf iBasic >= 5000 Then
varVal = iBasic * (40 / 100)

varVal = iBasic * (50 / 100)
End If
[DA].Text = varVal
If (iBasic + [DA]) >= 6500 Then
varVal = 720
varVal = Round((iBasic + [DA]) * (12 / 100), 0)
End If
[PF].Text = varVal
End Sub

Creating Query by QueryDef

' Defines a database and querydef object

Dim dbs As Database, qdf As QueryDef

Dim strSQL As String
Database Management System For Private Circulation only

' Set current database to dbs.

Set dbs = CurrentDb

' Refresh all Query Definitions in your current database.


' Before creating a Query you must check weather the query exists or not. If it ' exists
Delete it first. Here we are going to create a ‘SampleQuery’. Check for ' that –
‘SampleQuery’ query exists then delete it.
For Each qdf In dbs.QueryDefs
If qdf.Name
qdf = "SampleQuery" Then
dbs.QueryDefs.Delete qdf.Name
End If
Next qdf

' Create SQL string to select employees joined on a date which is entered in a
' textbox named ‘TxtQryDateOfJoin’ in the current form

strSQL = "SELECT * FROM Personnel WHERE “ & _

" (((Personnel.Dateofjoin)=#" & TxtQryDateOfJoin & "#));"

' Create new QueryDef object.

Set qdf = dbs.CreateQueryDef("SampleQuery", strSQL)

' Open query in Datasheet view.

DoCmd.OpenQuery qdf.Name
Set dbs = Nothing

NB: - if Error occurs include the library form the Tools ⇒ References… in the VBA code
window and choose “Microsoft Library”.
Microsoft DAO 3.6 Object Library

Creating Table by TableDef

Dim dbsNew As Database

Dim tdfNew As TableDef
Dim prpLoop As Property

' you can create table in current database or in another database. Use any one of
' the following Syntax
' Set dbsNew = CurrentDb
Set dbsNew = OpenDatabase("Sample.mdb")

' Create a new TableDef object.

Set tdfNew = dbsNew.CreateTableDef("Contacts")

With tdfNew

' Create fields and append them to the new TableDef Object.
' This must be done before appending the
Database Management System For Private Circulation only

' TableDef object to the TableDefs collection of the database.

.Fields.Append .CreateField("FirstName", dbText)

.Fields.Append .CreateField("LastName", dbText)
.Fields.Append .CreateField("Phone", dbText)
.Fields.Append .CreateField("Notes", dbMemo)

' Append the new TableDef object to the database.

dbsNew.TableDefs.Append tdfNew

End With

' If you want to delete new TableDef object then use the following syntax

' dbsNew.TableDefs.Delete "Contacts"

Searching Records By Using Loops.

For.. [ Step n ] …. Next [ Var ]

Dim db As New ADODB.Connection

Dim rs As New Recordset
Dim TotRec As Long
Dim i As Long

db.Provider = "Microsoft.jet.oledb.4.0"
db.Open "Access1.mdb"
rs.ActiveConnection = db
rs.Open "Personnel", , adOpenKeyset, adLockOptimistic
TotRec = rs.AbsolutePosition

For i = 1 To TotRec Step 1

Debug.Print rs.Fields(1)

Do While…. Loop

Dim db As New ADODB.Connection

Dim rs As New Recordset

db.Provider = "Microsoft.jet.oledb.4.0"
db.Open "Access1.mdb"
rs.ActiveConnection = db
' rs.Open "Personnel", , adOpenKeyset, adLockOptimistic
Set rs = db.Execute("Select * from Personnel")

Do While Not rs.EOF

Debug.Print rs.Fields(1)
Database Management System For Private Circulation only


Do Until…. Loop

Dim db As New ADODB.Connection

Dim rs As New Recordset
Dim TotRec As Long
Dim i As Long
db.Provider = "Microsoft.jet.oledb.4.0"
db.Open "Access1.mdb"
rs.ActiveConnection = db
rs.Open "Personnel", , adOpenKeyset, adLockOptimistic
TotRec = rs.AbsolutePosition

Do Until rs.EOF
Debug.Print rs.Fields(1)

Looping Statements
Looping statements are used for iteration. Suppose if you want to execute a particular set
of code repeatedly we can use looping statements.
The important looping statements in VB are
For counter = startvalue To endvalue [Step
Step stepvalue]
Exit For]
Next [counter]

For Each element In group
Exit For]
Next [element]
Select Case.…Case is…. Case else
Executes one of several groups of statements, depending on the value of an expression.
Select Case testexpression
Case expressionlist-n
[statements-n]] ...
Case Else
End Select
For changing the colour fo a textbox named TxtChoice
Private Sub CmdBtnCgClr_Click()
Dim choice As Variant
choice = TxtChoice.Text
Select Case choice
Case 1, "R", "r"
TxtChoice.BackColor = vbRed
Database Management System For Private Circulation only

Case 2, "G", "g"

TxtChoice.BackColor = vbGreen
Case 3
TxtChoice.BackColor = vbBlue
Case 4
TxtChoice.BackColor = vbMagenta
Case 5
TxtChoice.BackColor = vbBlack
Case 6, "a" To "f", "A" To "F"
TxtChoice.BackColor = vbYellow
Case Is >= 7, 0
TxtChoice.BackColor = vbWhite
Case Else
TxtChoice.BackColor = vbCyan
End Select

End Sub

IF Control statement
Conditionally executes a group of statements, depending on the value of an expression.
If <condition> then
Statement 2

Statement n
End If

If <Condition> Then
End if

If <Condition> then
Elseif <Condition> then
Elseif <Condition> then

End If

If <Condition> then
If <condition> then
End if
If <Condition> then
Database Management System For Private Circulation only

Elseif <Condition> then

End if
End if
and so on……

Looping Statements
Looping statements are used for iteration. Suppose if you want to execute a particular set
of code repeatedly we can use looping statements.
The important looping statements in VB are
For counter = startvalue To endvalue [Step
Step stepvalue]
Exit For]
Next [counter]

For Each element In group
Exit For]
Next [element]

Automate Repetitive Tasks in Microsoft Access

Put Macros and Visual Basic for Applications to Work in Your Forms

When you set up a database, You'll want it to be as easy to use as possible, especially
when it comes to repetitive tasks like data entry. With Microsoft Access, it's easy to
automate tasks like changing values in one field when the value in another changes or
printing reports by creating macros or writing Visual Basic.

a) Create a Macro to Change a Field's Value

When you find yourself repeating the same tasks, such as change (update) the value in
DA very time you change the value in Basic Pay. Your action, changing the Basic Pay,
causes an event to occur (in macro language, an AfterUpdate event). By creating a
macro, you can tell Microsoft Access which action you want it to take when this event

Creating a macro is easy with the Macro Builder. Open the form in Design view by clicking
the Database Window button, clicking the Forms tab, clicking the Salary form, and then
clicking Design. Click the Basic Pay box, click the Properties button, and then click the
Event tab.

In the After Update property box, click the Build button, and then double-click Macro
Builder to create a new macro.

Click the action that you want the macro to perform here (SetValue).
Then type the name of the control you want to change in the item box. (DA)
Type the expression (=[basic pay]*16/100) in the expression box
Database Management System For Private Circulation only

Click the Save button to save the macro whenever the Basic Pay changes.

Respond to other common events You can create macros that tell Microsoft Access what
to do when a user opens a form (the Open event), moves from one record to another (the
Current event), or clicks a specific button (the Click event), among other things.

What other actions can a macro perform? A macro can display a message to the user (the
MsgBox action), perform a Microsoft Access menu command (the DoMenultem action), or
simulate typing on the keyboard (the SendKeys action), among other actions. For details
on any macro action you see in the Macro window, click the action and press Fl.

Want a macro to perform a series of actions in response to a single event? Select each
action you want to perform in a separate row of the Macro window. Microsoft Access
performs the actions row by row.

b) To create a macro to perform a Export

Export a table to Excel and a Message

Select Macro Sheet Tab and Press New

i) First Action Item

In the Action Column select TransferSpreadSheet

In the action argument
Select Tranfer type as Export
Select Spreadtype as Microsoft Excel97
Select Table name as Salary
Select File name as SalaryExcel

ii) Second Macro Action

In the Action Column select MsgBox
In the action argument
Message box : Type the message you required “

Close the macro with a name and run the macro for the Actions.

c) Add a Command Button That Prints a Report

Do you frequently print a report after updating your database? Add a button to your form
that automatically prints the report.
Creating buttons that perform actions is easy with the Command Button Wizard. If you
haven't opened the Salary form in Design view, do so. In the toolbox, click the Command
Button tool, and if the Control Wizards tool isn't selected, click it, too. Click where you
want to put the button, and then follow the wizard's instructions.

Action Categories: Select Report Operations

Actions: Select Print Report and tell the wizard what you want the button to do

Save the form. Open the form and press the button and see what the command button do.

Note: Use the Command Button Wizard to create buttons that perform many other
actions Buttons can automatically open other forms, move between records, and add or
delete records, among other things. For details, look up command buttons, creating in the
Microsoft Access online index.
Database Management System For Private Circulation only

A report is an effective way to present your data in a printed format. Because you have
control over the size and appearance of everything on a report, you can display the
information the way you want to see it.

As in the case of a form you can create a report from a table, select query or a parameter
query. You can preview the report from the report sheet tab or adding command buttons
in the form for report operations.

In a report you can add different sorting, grouping/sub grouping levels. You can take
summary options of different numeric fields.

Create a report for seeing the designation wise list of employees.

1. In the Reports sheet click new button and select report wizard option.
2. Select the Personnel table in the combo box below and click ok
3. Select fields require for creating the report as in the case of form.
a) If you want to add fields from more than one Table/Query select the required
table/Query from the combo box shown above - only after selecting the required
fields of the current table/query.
4. Click Next> and select a filed name by which you group the data. Here we use
“Designation” field. (You can use Department, Caste, Religion, and Sex etc for
grouping). If you want to display Department wise Designation wise list add two
grouping levels. First level Department and second Designation and so on.

5. Click next and choose a key field name for sorting say basic. Then click on the button
labeled A/Z with an arrow on the right for selecting the sort order. AZ for ascending
and ZA for descending.
6. Select a secondary key field -say Name - if more than employee with same basics.
7. Select a sort order and so on
8. Click Summary option button and check (click) the corresponding for taking sum,
average, maximum etc.
9. Select a layout of your report - say block. Check other options like landscape/portrait
etc if you required.
10. Select a style from the next step – say formal
11. Give report name and finish it.
12. In this report you can see only the designation code. How can you bring the
designation here?
13. For that you select the designation field from the designation table while you are
creating the report in wizard. Another way for that is to create a query from Personnel
table and designation table and add required fields. Create a report from that query.
14. Take the design view of your report and check the Report/Page header, Designation
header, details and corresponding footers. Arrange them properly.
Reports in design view
1. Reports⇒Create Reports in Design View⇒Design
2. Right click at top left corner of report as shown in figure(Black Spot) and choose

3. Record Source⇒Select Query/Table (Personnel Table)

4. Drag all fields from field list window (View⇒Field List) the center of Detail session
5. Arrange them properly at detail session for columnar report. For tabular report
select all Labels and cut (Edit⇒Cut).
a) Click on Page Header session and Paste (Ctrl+V)
b) Properly arrange the Labels in the Page header session in a single line.
c) Arrange display controls in the Detail session properly as shown in figure.
d) View⇒Report Header/Footer
Database Management System For Private Circulation only

e) Add a Label from Tool box (Aa) at the Report Header session and type a
suitable Caption for your Report.
f) Add a Text box (ab|) at Page Footer session.
g) Delete the Label portion of it.
h) For Page number type, ="Page " & [Page] & " of " & [Pages]

i) Add One more textbox at Report Footer session

j) Delete its label part
k) For finding the sum of basic pays of all employees type,, ="Sum of Basic
Pays= " & Sum([BasicPay])

Save Report and preview.

Adding Grouping Levels in report design view

For creating designation wise list of employees first create a query from Personnel and
Designation table. Add Designation from Designation table along with the fields from
personnel. Save the query. Design report and assign the query as Record source.

1. View⇒Sorting and Grouping

2. Select Designation in the Filed/Expression
3. Select sort order, Ascending
4. Group header⇒Yes and Group Footer⇒Yes
5. Now you can see a group header Designation Header and Group Footer, Designation
Footer in the Report.
6. Drag the Designation Display control from Detail session to the Designation header.
7. Format it for Bold, Font Colour etc.
8. Delete Designation Label from Page Header Session
9. if you want to take count or sum of basic pay etc add text box at Designation Footer
Database Management System For Private Circulation only

10. the type expression in the text box as =Sum([BasicPay])

or =count([EmpCode]) etc
11. For adding serial numbers for detailed records in each designation we can perform the
following option
12. Add a textbox at a suitable place. Delete the label of it.

13. Type =1 in the textbox

14. place it at the left of EmpCode field at the Detail session
15. right click on the textbox and choose properties
16. Data⇒Control Source⇒ =1
17. Running Sum⇒Over Group
18. save and preview the result
19. After seeing the report, redesign it
20. select the properties of the serial number textbox
21. change the Running sum property to Over all
22. Save and preview the report again.