Working with Data Tables and Queries The first section of the book contains seven chapters that will teach you all aboutdata and conceptual designs of information... Chapter 1 contains g
Trang 4Access 2003 Bible Cary N Prague, Michael R Irwin, and Jennifer Reardon
Trang 5Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana
ISBN: 0-7645-3986-8
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/RX/QZ/QT/IN
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700 Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail:
permcoordinator@wiley.com.
is a trademark of Wiley Publishing, Inc.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CREATED
OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS
OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S at 800-762-2974, outside the U.S at 317-572-3993 or fax 317-572-4002.
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic books.
Library of Congress Control Number: 2003101923
Trademarks: Wiley and related trade dress are registered trademarks of John Wiley & Sons, Inc., and/or it affiliates, in the
United States and other countries, and may not be used without written permission All other trademarks are the property
of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Trang 6industry He owns Database Creations, Inc., the world’s largest Microsoft Accessadd-on company Their products include a line of financial software; Business! forMicrosoft Office, a mid-range accounting system, POSitively Business! Point of Salesoftware, the Inventory Barcode manager for mobile data collection, and the CheckWriter and General Ledger Database Creations also produces a line of developertools including the appBuilder, an application generator for Microsoft Access, the
EZ Access Developer Tools for building great user interfaces, appWatcher for taining code bases among several developers, and Surgical Strike, the only PatchManager for Microsoft Access
main-Cary also owns Database Creations Consulting, LLC., a successful consulting firmspecializing in Microsoft Access and SQL Server applications Local and nationalclients include many Fortune 100 companies including manufacturers, defense con-tractors, insurance, health-care, and software industry companies His client listincludes Microsoft, United Technologies, ABB, Smith & Wesson Firearms, Pratt andWhitney Aircraft, ProHealth, OfficeMax, Continental Airlines, and other Fortune 500companies
Formerly, he has held numerous management positions in corporate informationsystems, including Director of Managed Care Reporting for MetraHealth, Director ofCorporate Finance and Software Productivity at Travelers Insurance where he wasresponsible for software support for 35,000 end users, and Manager of InformationSystems support for Northeast Utilities
He is one of the top best-selling authors in the computer database managementmarket, having written over 40 books that have sold over one million copies onsoftware including Microsoft Access, Borland (Ashton-Tate) dBASE, Paradox,
R:Base, Framework, and graphics Cary’s books include 11 books in the Access Bible
series (recently number one on the Ingram Bestselling Database Titles list and in
the Amazon.com top 100), Access 97 Secrets, dBASE for Windows Handbook, dBASE
IV Programming (winner of the Computer Press Association’s Book of the Year
award for Best Software Specific Book), and Everyman’s Database Primer Featuring
dBASE IV He recently completed several books for Access 2003 including Weekend Crash Course in Office Access 2003 Programming Cary recently sold a product line
named eTools for Microsoft Access to MightyWords, a division of FatBrain.com andBarnes and Noble
Cary is certified in Access as a Microsoft Certified Professional and has passed theMOUS test in Access and Word He is a frequent speaker at seminars and confer-ences around the country He is on the exclusive Microsoft Access Insider AdvisoryBoard and makes frequent trips to Microsoft headquarters in Redmond, WA He hasbeen voted the best speaker by the attendees of several national conferences.Recently, he was a speaker for Microsoft sponsored conferences in New Orleans,
Trang 7He is active in local town politics serving on the South Windsor, Connecticut Board
of Education, Parks and Recreation Commission, and the Board of AssessmentAppeals
Cary holds a master’s degree in computer science from Rensselaer PolytechnicInstitute, and an M.B.A and Bachelor of Accounting from the University of
Connecticut He is also a Certified Data Processor
Michael R Irwin is considered one of the leading authorities on automated database
and Internet management systems today He is a noted worldwide lecturer, a winner
of national and international awards, best-selling author, and developer of
client/server, Internet, Intranet, and PC-based database management systems
Michael has extensive database knowledge, gained by working with the MetropolitanPolice Department in Washington, D.C as a developer and analyst for the InformationSystems Division for over 20 years and assorted Federal Agencies of the United StatesGovernment Since retiring in June 1992, he runs his own consulting firm, named TheIrwin Group, and is principal partner in the company - IT in Asia, LLC, specializing inInternet database integration and emphasizing Client/Server and net solutions Withconsulting offices in Cincinnati, Ohio, Bangkok, Thailand, and Manila, Philippines, hiscompanies offer training and development of Internet and database applications His company has the distinction of being one of the first Microsoft Solution’s
Providers (in 1992) His local, national, and international clients include many ware companies, manufacturers, government agencies, and international companies
soft-His range of expertise includes database processing and integration between frame, minicomputer, and PC-based database systems, as well as B-2-B and B-2-Cintegration between back-end databases; he is a leading authority on PC-baseddatabases
main-He is one of the top best-selling authors in the computer database management ket, having authored numerous database books, with several of them consistently
mar-on the best-sellers lists His books, combined, have sold nearly a millimar-on copies
worldwide His most recent works include The OOPs Primer (Borland Press, dBASE
5.5 for Windows Programming (Prentice Hall), Microsoft Access 2002 Bible, Microsoft Access 2002 Bible Gold Edition (co-authored), and Working with the Internet The Access Bible series have constantly been number one on the Ingram Best-selling
Database Titles list and is consistently in the Amazon.com and Buy.com top 10 Hehas also written several books on customs and cultures of the countries of Asia
Trang 8He is a frequent speaker at seminars and conferences around the world and hasbeen voted the best speaker by the attendees of several international conferences.
Michael has developed and markets several add-on software products for theInternet and productivity related applications Many of his productivity applicationscan be obtained from several of his Internet sites or on many common downloadsites Many of his application and systems are distributed as freeware and careware
He has also developed and distributes several development tools and add-ins for awide range of developer applications
Jennifer Reardon is considered a leading developer of custom database
applica-tions She has over ten years’ experience developing client/server and PC-basedapplications She has accumulated much of her application development experi-ence working as lead developer for Database Creations She has partnered withCary Prague developing applications for many Fortune 500 companies
Her most significant projects include a spare parts inventory control system forPratt & Whitney’s F22 program, an engineering specifications system for ABB-Combustion Engineering, and an emergency event tracking system for the State ofConnecticut She was also the lead developer of many of the Database Creationsadd-on software products including Business, Yes! I Can Run My Business, CheckWriter, and the User Interface Construction Kit
She has co-authored Access 2003 Bible, Access 2002 Bible, and Access 2000 Weekend
Crash Course She has also written chapters in other books on subjects including
Data Access Pages, the Microsoft Database Engine, the VBA programming ment, creating help systems, and using Microsoft Office 2000 Developer She hasauthored chapters in Microsoft Access 97 Bible and Access 97 Secrets
environ-Jennifer owns her own consulting firm, Advanced Software Concepts, providing tom applications to both the public and private sectors She specializes in develop-ing client information systems for state-managed and privately-held healthcareorganizations She has also developed a job costing and project management sys-tem for an international construction company Her corporate experience includesseven years with The Travelers where she was an Associate Software Engineer serv-ing on numerous mission-critical client/server software development projects usingEasel, C, SQL Server, and DB2 She has contributed several chapters for books ondBase and Microsoft Access
cus-Jennifer holds a Bachelor of Science degree from the University of Massachusetts
Trang 9Graphics and Production Specialists
Beth Brooks, Amanda Carter, JenniferClick, Joyce Haughey, Barry Offringa, Lynsey Osborn, Heather Pope
Quality Control Technicians
Carl William PierceBrian H Walls
Senior Permissions Editor
Carmen Krikorian
Media Development Specialist
Angela Denny
Proofreading and Indexing
TECHBOOKS Production Services
Trang 10Manager Matt Galligan, John Mitchell, Barbara Barbour, Walter Mealy, Herb Asplund, Roy Normen, Jan Murtha, Bob Wilson, Hap Fitts, and many others in the South Windsor Republican Town Committee Craig Zimmerman of the South Windsor Parks and Recreation Commission, Ray Favreau, Mike McCarty, and Elle Randazzo of the South Windsor Recreation Department, Joel Nadel of the Board of Assessment Appeals and Charlie Dana, Assessor, Anne Flint and Gabrielle Batz of the South Windsor Chamber of Commerce, and Dr Joseph Wood, Superintendent of Schools By allowing
me to explore new opportunities and shamelessly promote myself, you have enriched my life and provided me with new friends and new challenges
that I never knew existed.
— CNP
This book is dedicated to the people closest to me First and foremost it is dedicated to
my family — my wife, Dra Arni Irwin, my sons Richard Rocco, Joseph Patrick, and David Joseph While writing this book, they had to put up with my constantly telling them “Sorry, I have to do this first” in order for me to finish on deadline It is also dedicated to my mother, Aurelia Irwin — 74 years young and as strong as ever — who has continued to be my sounding board and example of strength Finally, partner,
Richard Mahonski, who passed away this year — I will truly miss him.
— MRI
This book is dedicated to my parents-in-law Tom and Arden Reardon Way back during
my college years, they provided me with the unique opportunity to be involved in the world of publishing as a part-time typesetter for their respective printing businesses Together, we forged a method of setting type using my PC and modem and their Mergenthalers — this was 1983 — much before the era of desktop publishing as we know it today Now here I am enjoying being on the other side of the fence as an author But, all the while that I am keyboarding my own work, I am always thinking back to the old days of how we used to have to keyboard all those crazy codes for font changes and em spaces and line spacing Thanks for always being so supportive of me
in the past 30 years that I have been part of your family.
— JR
Trang 12Welcome to the Access 2003 Bible — your personal guide to a powerful,
easy-to-use database management system This book is in its ninth revision andhas been totally re-written for Microsoft Office Access 2003 with new text, new pic-tures, and a completely new and improved set of example files
This book examines Access 2003 with more examples than any other Access bookever written We think that Microsoft Access is an excellent database manager andthe best Windows database on the market today Our goal with this book is to sharewhat we know about Access and, in the process, to help make your work and yourlife easier
This book contains everything you need in order to learn Microsoft Access to amid-advanced level You’ll find that the book starts off with the basics and builds,chapter by chapter, on topics previously covered In places where it is essentialthat you understand previously covered topics, we present the concepts again andreview how to perform specific tasks before moving on Although each chapter is
an integral part of the book as a whole, each chapter can also stand on its own andhas its own example files You can read the book in any order you want, skippingfrom chapter to chapter and from topic to topic (Note that this book’s index is par-ticularly thorough; you can refer to the index to find the location of a particulartopic you’re interested in.)
The examples in this book have been well thought out to simulate the types oftables, queries, forms, and reports most people need to create when performingcommon business activities There are many notes, tips, and techniques (and even
a few secrets) to help you better understand the product
This book can easily substitute for the manuals included with Access In fact, manyusers do not get manuals today, often relying on just the online help This book willguide you through each task you might want to do in Access We even createdappendixes to be used as reference manuals for common Access specifications.This book follows a much more structured approach than the Microsoft Accessmanuals, going into more depth on almost every topic and showing many differenttypes of examples
Trang 13Is This Book for You?
We wrote this book for beginning, intermediate, and even advanced users ofMicrosoft Access 2003 With any product, most users start at the beginning If, how-ever, you’ve already read through the Microsoft Access manuals and worked withthe Northwinds sample files, you may want to start with the later parts of this book.Note, however, that starting at the beginning of a book is usually a good idea so youdon’t miss out on the secrets and tips in the early chapters
We think this book covers Microsoft Access in detail better than any other bookcurrently on the market We hope you will find this book helpful while working withAccess, and that you enjoy the innovative style of a Wiley book (formerly IDG
Books, the people who make the For Dummies books).
Yes — If you have no database experience
If you’re new to the world of database management, this book has everything youneed to get started with Microsoft Access It then offers advanced topics for refer-ence and learning
Yes — If you’ve used other database managers like dBASE or Filemaker
If you’re abandoning another database (such as dBASE, Filemaker, Alpha, Paradox,FoxPro, R:Base) or even upgrading from Access 2.0, Access 95 or 97, or evenAccess 2000 or 2002 this book is for you You’ll have a head start because you’realready familiar with database managers and how to use them With MicrosoftAccess, you will be able to do all the tasks you’ve always performed with character-based databases — without programming or getting lost This book will take youthrough each subject step by step
Yes — If you want to learn the basics of Visual Basic Applications Edition (VBA) programming
VBA has replaced the Access Basic language We know that an entire book is needed
to properly cover VBA, but we took the time to put together many chapters thatbuild on what you learn in the forms chapters of this book The VBA programmingchapters use the same examples you will be familiar with by the end of the book
Conventions Used in This Book
✦ When you are instructed to press a key combination (press and hold downone key while pressing another key), the key combination is separated by a
Trang 14plus sign Ctrl+Esc, for example, indicates that you must hold down the Ctrl
key and press the Esc key; then release both keys
✦ Point the mouse refers to moving the mouse so that the mouse pointer is on a
specific item Click refers to pressing the left mouse button once and releasing
it Double-click refers to pressing the left mouse button twice in rapid
succes-sion and then releasing it Right-click refers to pressing the right mouse
but-ton once and releasing it Drag refers to pressing and holding down the left
mouse button while moving the mouse
✦ When you are instructed to select a menu, you can use the keyboard or the
mouse To use the keyboard, press and hold down the Alt key (to activate the
menu bar) and then press the underlined letter of the menu name; press Alt+E
to select the Edit menu, for example Or you can use the mouse to click on the
word Edit on-screen Then, from the menu that drops down, you can press the
underlined letter of the command you want (or click on the command name)
to select it
✦ When you are instructed to select a command from a menu, you will often see
the menu and command separated by an arrow symbol Edit_Paste, for
exam-ple, indicates that you need to select the Edit menu and then choose the Paste
command from the menu
✦ Italic type is used for new terms and for emphasis.
✦ Bold type is used for material you need to type directly into the computer.
✦A special typefaceis used for information you see on-screen — error
mes-sages, expressions, and formulas, for example
Icons and Alerts
You’ll notice special graphic symbols, or icons, used in the margins throughout this
book These icons are intended to alert you to points that are particularly
impor-tant or noteworthy The following icons are used in this book:
This icon highlights a special point of interest about the topic under discussion
This icon points to a useful hint that may save you time or trouble
This icon alerts you that the operation being described can cause problems if
you’re not careful
Caution
Tip
Note
Trang 15This icon highlights information for readers who are following the examples andusing the sample files included on the disk accompanying this book.
This icon calls attention to new features of Access 2003
How This Book Is Organized
This book contains 39 chapters divided into four main parts and five sections Inaddition, the book contains a fifth part containing four appendixes
The main parts of the book include:
✦ Creating Desktop Applications
✦ Creating Enterprise Applications
✦ Creating Web Applications
✦ Advanced Topics
Part I: Creating Desktop Applications
Part I consists of three sections and for most Access users is all that you will everneed The 26 chapters in this section (or about two-thirds of the book) cover every-thing you will need to do for your individual or workgroup applications includingcreating data tables, building forms and reports, and programming in VBA
Working with Data Tables and Queries
The first section of the book contains seven chapters that will teach you all aboutdata and conceptual designs of information
Trang 16Chapter 1 contains great conceptual material on understanding the basic elements
of data, introduces you to the buzzwords of database management, teaches you how
to plan a table and will show you the different data types Chapter 2 teaches you
how to create a table You learn how to properly name fields and assign data types
You will learn how to rename fields and add fields to an already created table
Chapter 3 covers everything you need to know about entering data into forms and
datasheets You will learn how to add validation to fields, format fields and use
vari-ous built in tools for making data entry easier You will learn how to search for data
and how to change and delete data values In Chapter 4 you will learn more about
creating tables and creating primary and foreign keys and relating them and using
the Relationship builder tools in Access In Chapter 5, you examine the concept of
queries; then you create several queries to examine how data can be filtered,
rearranged and displayed Chapter 6 continues the query work started in the
previ-ous chapter, You will learn how to create more complex criteria to ask questions
about your data You will learn a little about SQL and WHERE clauses and how to use
operators and expressions Chapter 7 examines how to import, export, and attach
external files, and how to copy Access objects to other Access databases
Building Forms and Reports
The second section of the book contains ten of the most in-depth chapters ever
written on forms and reports
You’ll begin in Chapter 8 with a visual tour of various types of forms and get a
com-plete understanding of form controls Chapter 9 teaches the basics of creating
data-entry forms and using Wizards to simplify the creation process; using data-data-entry
forms is also discussed Chapter 10 examines the concepts of bound forms to table
data sources and how to create unbound forms Chapter 11 teaches how to add
data validation to forms to prevent errors It also teaches the basics for combo box
controls Chapter 12 teaches you how to professionalize the look for forms and
reports through various formatting techniques and the use of color and special
visual effects to create great-looking forms and reports that catch the eye and
increase productivity Chapter 13 covers the basics of report creation and printing
and introduces groups which allow reports to summarize data at many levels
Chapter 14 covers embedding subforms in forms and reports and how to link a
par-ent form to a child form within a subform Chapter 15 shows you how to create
summaries and totals in reports and how to work with various group headers and
footers Chapter 16 discusses the various special reports types such as snaked
col-umn reports for directories, mail merge reports and labels Chapter 17 explains the
use of pictures, graphs, sound, video, and other OLE objects
Automating Your Applications
The third section of the book covers VBA programming and how to use Visual Basic
commands to control forms and reports and to build outstanding user interfaces
Chapter 18 teaches the concepts of Visual Basic programming and how to edit a
Visual Basic procedure Chapter 19 covers the concept of event-driven
program-ming and how Access uses commands to automate manual processes Chapter 20
Trang 17manipulating strings to formatting dates In Chapter 21 you learn about ADO andrecordsets used to move data between forms and tables This chapter is the mostimportant chapter for programmers in understanding database management,Chapter 22 teaches you how to craft programming commands to find data You willlearn how to automate queries and link combo box selection to display data on aform Chapter 23 teaches how to use subroutines to create reusable code modulesfor more efficient coding Chapter 24 teaches you how to add error routines andproper debugging routines for programs In Chapter 25, you learn how to createbutton menus known as switchboards, as well as traditional pull-down menus, andcustom command bars used to build menus and toolbars Chapter 26 teaches how
to create a tab control and use continuous forms to display and switch betweendata views
Part II: Creating Enterprise Applications
This fourth section of the book teaches how to build applications an entire prise can use
enter-Chapter 27 teaches the process of upsizing Access tables to SQL Server You learnhow to use the upsizing wizard and all the tasks you need to do to really make itwork While chapter 27 teaches how to upsize your data, chapter 28 teaches how tocreate an Access Data Project (ADP) to create a true client-server system You learnhow to upsize your programs and create ADO recordsets to work against SQLServer or the Microsoft Database Engine (MSDE) Chapter 29 delves further into theclient server world teaching how to create stored procedures, triggers and pass-through queries to build true client server systems
Part III: Creating Web Applications
The three chapters of section four cover building applications that work with data
on the internet and with intranets Chapter 30 covers building basic Data AccessPages (DAP) using many of the example you are already familiar with Chapter 31covers more advanced types of DAP’s Chapter 32 provides an overview of XML andschemas and also includes an overview of the new InfoPath product used to createforms with XML data
Part IV: Advanced Access Database Topics
This part contains six chapters that present advanced topics on each of the basictasks of Access Chapter 33 examines how to exchange data with other Office prod-ucts such as Word, Excel, Outlook and even PowerPoint Chapter 34 covers securityand protecting a database while chapter 35 shows you how to build and run helpsystems Chapter 36 discuss advanced select query topics, including total, cross-tabulation, top-value, and union queries Chapter 37 covers action queries, which
Trang 18change data rather than simply displaying records Chapter 37 is also a
com-pendium of advanced query topics that will leave you amazed at the power of
Access Chapter 38 shows you a multitude of techniques for increasing the speed
of an application Finally, Chapter 39 covers the new Access Developers Edition
(ADE) and runtime
Part V: Appendixes and Reference Material
The last part contains four appendixes Appendix A presents a series of tables
list-ing Access specifications, includlist-ing maximum and minimum sizes of many of the
controls in Access Appendix B displays a database diagram of the many database
tables used in this book so you can create your own system Appendix C describes
the CD-ROM Appendix D is a discussion of standard naming conventions
Guide to the Examples
The examples in Access 2003 Bible are specially designed to maximize your learning
experience Throughout this book you will see many examples of good business
table design and implementation, form and report creation, and module coding in
Visual Basic You will see examples that use both Jet (the internal database of
Microsoft Access) as well as examples that connect to SQLServer datbases You will
also see forms that work on the Web using Access’s own Data Access Pages
As every developer knows, it is important to understand what you are creating and
programming from the application standpoint This is sometimes called the business
of business, and in this book we have chosen a simple example that any business
or developer can hopefully relate to More importantly, in this or any book you
must relate to it successfully in order to learn When developing systems you often
find yourself analyzing applications that you don’t have a lot of experience with
Obviously an aerospace engineer makes a better analyst when developing a system
to track airplane engines, but any good developer can develop any system as long
as they are willing to work with the business experts In this book, the authors and
their words will serve as the business experts
The examples in this book will use a fictitious company named Access Auto Auctions
or AA Auctions for short AA Auctions buys and sells cars, trucks, and other vehicles.
They directly sell these vehicles and also offer them for sale through auctions both at
their equally fictitious showroom and on the Internet The example database contains
the necessary tables, queries, forms, reports and module code to facilitate their
busi-ness needs
Within this guide we are going to use some terms that have not been thoroughly
been explained yet Feel free to skip over them and return to this guide often as
you start new chapters that use these forms and reports
Note
Trang 19While professional developers will always split program and data objects into twoseparate database files, it is acceptable during development to combine all of theobjects into one database and split them when development is complete Whenyou are working in a program database and you are linked to your data file, youmust load the data database file before you can make changes to the table design.You’ll learn more about this throughout the book.
The Main Menu Switchboard
When you load the completed example file (Access Auto Auctions.mdb), you willsee the main menu (known as a switchboard) shown in Figure FM-1 This switch-board contains buttons that display the main areas of the system
Tip
Using the Example Files on Your CD
On your CD is a standard Windows setup program that will install the examples onto yourhard drive We have provided separate Microsoft Access database files for each chapter.They are arranged into subdirectories that are placed on your hard drive when you installthe example files The subdirectories are simply names Chapxx where xx is the chapternumber The database files are each named Chapxxyyyyyyy.mdb where xx is the chapternumber and yyyyyyy is a description of the contents For example, Chap07Start.mdb would
be the database file you might open at the start of Chapter 7 and Chap07End.mdb would be how you would expect to find the database after you completed all of the exer-cises in the chapter Some chapters will have no files while others may have many.Additionally, you may find other types of files with their own file extensions in each subdi-rectory You will be instructed how to use each file throughout each chapter of the book.Additionally, we have provided many fully working programs, demos, and trial versions ofsome of the best Microsoft Access tools for end-users and developers and provided links tothese companies’ websites so you can get the latest information from them
In each chapter’s database file, you will only see the objects that are needed for the ter We have also combined all the completed working forms and reports in two database
chap-files; AccessAutoAuctions.mdb contains all of the program objects (queries, forms, reports, and modules) The linked data file AccessAutoAuctionsData.mdb will contain
only the tables used by the application However, in the individual chapter files, you will seethe program files (queries, forms, reports, and modules) in the same database file as thetables
Trang 20Figure FM-1: The Access Auto Auctions main switchboard
that allows the user to open various forms and reports
These main areas include:
✦ Contacts: Buyers and Sellers of vehicles and parts that AA Auctions deal with.
Rather than traditionally separate Customer and Supplier tables, the Contacts
table provides a single access point to all people that AA Auctions needs to
contact for any reason
✦ Sales: This button displays an invoice form that lets AA Auctions enter
infor-mation about the buyer (which comes from the Contacts inforinfor-mation) It
allows for an unlimited number of line items on the Invoice Each item will be
selected from information stored in the Products system
✦ Products: Lists of everything that AA Auctions sells or offers for auctions
These include vehicles, parts, and anything that needs to be tracked for sales
or inventory purposes including descriptions, costs, selling prices, and even
pictures of each vehicle or part
✦ Reports: Any good application contains reports at many levels This button
actually does nothing Normally, it would be used to display a generic report
manager that displays reports while allowing specifications of the report
name and parameters which will only show data between certain dates or for
certain vehicle types Though not specifically covered in this book, on the
example CD of third party products, there is a generic report manager named
the ez Report Manager you can use
✦ Company Setup: This displays a form that contains information used by the
entire system This is used when you need global values such as your
com-pany name (Access Auto Auctions in this example) or other information that
can be used by the entire application
Trang 21Understanding the Data Tables
Data is the most important part of any system and in Access (as well as every otherdatabase management system), data is arranged into logical groupings known astables Tables help define the structure of the data as well as hold the data itself.Tables are related to each other in order to pass data back and forth and to helpassemble the chaos of data into well defined and formatted information
The diagram in Figure FM-2 displays a representation of most of the data tables thatmake up the Access Auto Auctions example As you will learn in Part 1 of this book,the lines, arrows, and symbols between the tables mean something important andcommunicates to the developer how the data interacts You will learn terms liketable, field, record, relationship, referential integrity, normalization, and primaryand foreign keys as you begin to understand how tables work within a database
Figure FM-2: The Access Auto Auctions data relationship diagrams showing the
example tables and their data fields
Why There Are Prefixes in Front of Table Names and Data Fields in the Relationship Diagram
You might notice that each table name is prefixed with the letters tbl You might also notice
that each data field listed in Figure FM-2 is also prefixed with a variety of characters These
are standard naming conventions, prefixes assigned by developers to let other developers
know the type of data these fields may contain when later used in Visual Basic programs.The characters tbl mean the object is a table There are other prefixes for database objectssuch as qry (query), frm (form), rpt (report), and mod (module) Some of the common datafield prefixes include chr (character), int (integer), dtm (date/time), and many others Youwill see that we use standard naming conventions throughout this book
Trang 22Naming conventions are more thoroughly discussed in Appendix D.
In the example database are approximately 11 tables as shown in Figure FM-2 that
are used to create the Access Auto Auction applications Many of the smaller tables
are lookup tables whose sole purpose is to provide a list of valid selections The
larger tables hold the data used by the system itself All of these tables include a
number of data fields that are used as the definitions of the data The lines between
the tables show how tables how related by common data fields If these terms are
strange to you, don’t worry In the first few chapters, you will receive a full
explana-tion of each of them The tables include:
✦ tblSales
• The tblSales table contains fields for the main part of the sale This
includes information that occurs once in the sale such as the InvoiceNumber, dates of the sale, the Buyer ID (which links to the tblcontactstable to retrieve information about the buyer including taxing informa-tion), the Salesperson ID (which links to the tblSalesperson table), thetaxing location (which links to the tblTaxRates table), and various otherfinancial information
✦ tblSalesperson
• The tblSalesPerson table contains a list of sales people that sell
prod-ucts for Access Auto Auctions along with their commission rates It islinked to the Sales Invoice and is used when a Salesperson is selected inthe Invoice form
✦ tblTaxRates
• The tblTaxRates table contains a list of taxing locations and tax rates
and is used by the Sales Invoice when the buyer is selected in the form
The taxing location is retrieved from tblTaxRates and then the tax rateused by the Invoice to calculate taxes owed
✦ tblSalesLineItems
• The tblSalesLineItems table contains fields for the individual line items
that will make up the sale The sale may contain a variety of items
Several vehicles may be sold to a single buyer at one time The buyermay buy parts, accessories, or services You will see a form created laterwhich allows for the data entry of an Invoice and an unlimited number oflineitems that will be stored in this table
• The data fields in the tblSalesLineItems table include the Invoice Numberwhich is used to link the main Invoice table to the Invoice Lineitemstable as well as the quantity purchased The Product ID field (which links
to the tblProducts table) is used to retrieve information about the uct including the item description, price, and taxability status A dis-count field allows a discount to be entered
prod-
Cross-Reference
Trang 23ory Rather than simply link from the tblSalesLineItems table to thetblProducts table by the common chrProductID field data values fromthe tblProducts table are copied to the tblSalesLineItems This is often
done with time-dependent data If a customer bought a part today with a
price of $10.00 and next week the price goes up to $15.00 as stored in thetblProducts table, it would be wrong if the Invoice then showed the price
of $15.00
You learn more about relational database theory and how to build tables inSection I of this book
✦ tblSalesPayments
• The tblSalesPayments table contains fields for the individual payment
lines The invoice may be paid for by a variety of methods The customermay make a deposit for the sale with a check, and then split the remain-ing amount owed with a variety of credit cards By having unlimited payment lines in the Invoice form you can do this
• The data fields in the tblSalesPayments table include the InvoiceNumber which is used to link the main Invoice table There is a field forthe payment type (which links to the tblPaymentType table) to onlyallow entry of valid payment types as well as the payment date, paymentamount, and any check or credit card number and the credit card expira-tion date
✦ tblPaymentType
• The table tblPaymentType is simply a lookup table with valid values for
types of payments Only valid payment types can be chosen for a payment
✦ tblContacts
✦ The table tblContacts contains information about all the people and
compa-nies that Access Auto Auctions will have relationships with This dataincludes customers, suppliers, buyers, and sellers Names, physicaladdresses, phone and fax numbers, email addresses and Web sites and all thefinancial information about the contact is stored in this table Unlike thetblSalesLineitems table information, this data is only linked from an Invoiceform and with the exception of some changing financial data is never copied
to any other table This way if a customer changes their address or phonenumber, any Invoice which is related to the contact data, will instantly showthe updated information
✦ tblContactLog
• The tblContactLog table contains potentially multiple entries for each
contact in the tblContacts table This information includes the contactdate, notes or items discussed, and follow up information The contactsform will manage all of this information
Cross-Reference
Trang 24✦ tblCustomerTypes
• The tblCustomerTypes table simply contains a list of valid customer
types that can be selected through the Contacts form It is important in
all applications that certain data be limited to valid values In this
exam-ple, each valid value will trigger certain business rules Therefore, data
entry must be limited to those values
✦ tblProducts
• The tblProducts table contains information about each item that is sold
or auctioned by Access Auto Auctions This table contains information
that is used by the Invoices line item section The products table could
also be used as an inventory table However, since Access Auto Auctions
will provide a wide variety of products and services, the term Products
seemed to suit it better
• The tblProducts table includes field data types of nearly every type
available in Access From a business viewpoint, there is a key field which
will be user defined The table contains a field for description and
sev-eral types of costs, prices and quantity fields There are also sevsev-eral
fields that determine if a value is true or false including whether or not
the item is being auctioned and whether it is taxable A date field is used
to display the auction end date There are also a field for long text values
(known as memo fields) for a list of features, and a field for a picture of
each vehicle
• The tblProducts table will be one of the main tables used in this book
The frmProducts form will be used to teach nearly all form development
lessons in the book so you should pay particular attention to it
✦ tblCategories
The tblCategories table is used to lookup a list of valid categories.
Understanding the Products Form
The frmProducts form shown in Figure FM-3 is the first form that will be used to
teach you how to properly build forms It is also one of the forms that you will use a
lot of through the book The Products form was developed with most of the form
control types used in Microsoft Access to handle table data types such as text,
cur-rency, date, yes/no, memo, and OLE pictures You will also learn how to use form
control types such as labels and text boxes, command buttons, option group
con-trols, check boxes, combo boxes, and toggle buttons You will learn how to use
lines and rectangles and all the special effects that go with them There is also a
tabbed dialog on the form which uses a subform control as well There is even a
popup calendar on the form You will see several different form types and
niques to enter, search, filter, retrieve, and display data The form includes
tech-niques to hide controls, display them based on certain business rules and even
update data in other tables This form will be used to teach you how to work with
long memo fields and pictures as well
Trang 25technical details of how to build it The form will contain information about eachproduct and is bound (tied to) the tblProducts table As you enter information intothe frmProducts form, it is stored in the tblProducts table You learn more aboutthat in Section II
You will learn how to resize controls, how to align and space controls You will learnhow to copy and paste controls, secrets of moving controls as well as how to workwith color, shading, text fonts, and even special effects The frmProducts form can
do all this and more Later, after you master forms, you will learn how to add codebehind this form and several others to make a truly powerful application You willlearn how to add code to the Invoice form to check to the quantity in stock beforeyou can sell an item and then change the quantity in stock after you have sold it
The top of the frmProducts form contains a control that allows you to quickly find a
record This Quick Find is programmed using VBA code behind a combo box
selec-tion The bottom of the form contains a series of command buttons that will beused to demonstrate how to create new records, delete existing records, and dis-play a custom search and custom print dialog
Figure FM-3: The Access Auto Auctions Products form which
allows data entry for all vehicles and parts sold or auctioned
Understanding the Product form subform
A form normally displays one screen of data The frmProducts form contains a tabcontrol This lets you effectively use a form to display many screens of data Eachcan use a different table or a different type of form The frmProducts form displays
a single record at a time This is on the first tab named Product The second tab named Show All Products displays many records at once as shown in Figure FM-4.
This is actually a subform or a form (named fsubProductsDisplayAll) within the
frmProducts form
Trang 26This form is another great example of how a form works It displays many records
at once but only selected fields Each record contains a button to switch between
the record in the second tab with the more detailed record in the first tab There is
also a button alongside each record to delete any records that are no longer
needed Each of the column headers are actually buttons with code behind them
that can be clicked on to sort the records displayed by the form One click and the
data in that column is used to sort the records in ascending order The next click
into descending order
Figure FM-4: The Access Auto Auctions Products form’s Show All Products tab that
allows the user to display all of the products and go right to the details of any record
Understanding the Contacts Form
The frmContacts form shown in Figure FM-5 is used to maintain information about the
various contacts that Access Auto Auctions has relationships with This includes
the contacts name and address, whether they are a buyer, seller, or both It includes
information if the buyer or seller is a car dealer or parts store that they regularly do
business with or someone who just once came to a auction, bid on a car, and won
The Contact form like the Products form contains a tab control This allows you to
show several screens within one form The Contacts form will be used in later
chap-ters to teach how to display objects within a form based on certain conditions It
will show how to use a calendar to store and display data as well Using information
on the other tabs, you will also learn how to display other forms such as a Contact
Log and how to synchronize information between two forms
Trang 27Figure FM-5: The Access Auto Auctions frmcontacts form showing
a tabbed dialog and values used with the tblContacts table
Using the Invoice form
The frmSales form shown in Figure FM-6 is used to teach some of the more
advanced form concepts you will learn in this book Unlike all the other forms, theInvoice form contains two subforms each of which use a relationship known as one-to-many This means that there may be one or more records in each subform thatrelate (use the same key) as the main form In this example, each invoice is used tosell one or more products to a buyer After all the products are selected for theinvoice and a total price is calculated, you can enter one or more payments to payfor the vehicle and any parts or accessories The buyer may make a deposit with acheck, and then pay the remaining balance with two different credit cards
This form will also be used to teach simple and complex calculations The tion of the Amount column in the invoice line items is Qty x Price x (1-Discount%)for example All of the amount records have to be totaled to calculate the subtotalfield Then a tax rate has to be retrieved and calculated to get the tax amount Thisplus the other amount must be summed to get the total All this is happening using
calcula-fields in the Invoice Line items (fsubSalesLineitems) subform
The second subform (fsubSalesPayments) will also be used to show how to calculate
a total in one subform (the total of all payments) and then use that total with controls
in other parts of the form This is how the Amount Due control will be calculated Itwill require data from the main form and both subforms to calculate its total
Trang 28These calculations will first be taught using nothing but properties of the controls
themselves without any VBA code in the earlier chapters You will learn many
tech-niques for control referencing and calculating between forms Later in the book,
you will learn how to add more flexibility and power by using VBA code to replace
the original techniques and then learn to use subroutines to really professionalize
the application
The Invoice form will also be used to teach several other important techniques
including displaying values in other forms as you are taught how to display a
prod-uct record by hiding a double click event in the prodprod-uct control of each lineitem.
Each line item and payment can also be deleted by using a button and the code will
be explained here as well The bottom of the Invoice form will also contain buttons
to create a new record a fill in any defaults as well as to delete an unneeded invoice
and to display search and print dialogs
Figure FM-6: The Access Auto Auctions Sales Invoice form used to
show multiple linked subforms and totals
Trang 29Understanding the Search Dialogs
Each of the main forms (Contacts, Products, Sales) can display a separate formknown as a dialog (a form that is displayed on top of another) This allows you tochoose from a variety of ways to search for a record This is built using a standardMicrosoft Access form It contains an option group to allow the user to select asearch type and then uses VBA code to assemble the desired records in a list box
as shown in Figure FM-7 Once the user selects the desired record and presses the
OK button, more VBA code is used to close the dialog box, and display the desiredrecord in the Invoice form There are separate search dialog forms for each of themajor forms
Figure FM-7: The Access Auto Auctions search
dialog displaying a variety of searches for the Invoice form
Understanding the Print Dialogs
Each of the main forms also use a separate form known as a dialog (a form that isdisplayed on top of another) to allow you to choose important print settings beforeprinting the report that has been created to go with each form In this example, you
can see the Invoice’s print dialog (frmDialogSalesPrint) as shown in Figure FM-8.
This form allows you to print invoices for just the current Inviice record, for aselected date range, or even all invoices for a specific buyer You will learn how tobuild this form and properly write the VBA code behind it This form will also teachyou how to filter data for reports, and to pass parameters to the Microsoft Accessprint routines You will learn how to send preview a report to the screen or how toprint any number of copies You will also learn how to print multiple reports atonce from this simple print dialog
There are separate print dialogs for each of the major forms
Trang 30Figure FM-8: The Access Auto Auctions invoice
print dialog displaying a variety of reports for
the Invoice form
As you go through each chapter, come back here to remember what you will learn
or where each form is In each chapter’s database file, you will only see the objects
that are needed for the chapter The main databases, AccessAutoAuctions.mdb and
its linked data file AccessAutoAuctionsData.mdb will contain the finished example
However, in the majority of all the chapter files, you will see the program files
(queries, forms, reports, and modules) in the same database file as the tables
Trang 32When we first saw Access in July of 1992, we were instantly sold on this
new-generation database management and access tool We have all spent thelast eleven years using Access daily In fact, we eat, breathe, live, and sleep Access!The fact that we can earn a living from our work on principally one product is atribute to the designers of Microsoft Access This product has changed the produc-tivity of corporations and private citizens of the world More people use this prod-uct to run their businesses, manage their affairs, track the most important things intheir lives, and manage data in their work and play than any other product everwritten It is indeed a privilege to be part of this worldwide community We havefound readers in every county on the map and a few countries we never heard of.The global Internet age has allowed readers in emerging countries, in the Himalayanmountains, in Siberia, and even in Antarctica to contact us this year
Now we have completely rewritten this book for Access 2003, with new examplesand more in-depth coverage We’ve covered every new feature we could think offor the beginning and intermediate users and especially enhanced our program-ming section Over 500,000 copies of our Access Bibles have been sold for all versions of Microsoft Access; for this we thank all of our loyal readers
Our first acknowledgment is to all the users of Access who have profited and fited beyond everyone’s wildest dreams
bene-There are many people who assisted us in writing this book We’d like to recognizeeach of them
To Greg Croy, whom we complain to each day Thanks for listening, Pilgrim
To all the people who really made this book possible To Andy Cummings at WileyPublishing, Inc., who pushes us beyond our limits The word NO is not in his vocab-ulary! He challenges us daily with impossible tasks and deadlines (I don’t care if thesoftware doesn’t work yet — write the book anyway, use your imagination — wemust get this book out first) Cary thinks he wants us to get started on the Access
2006 Bible next month (July 2003), although the software won’t be in beta foranother two years
Special acknowledgements go to our project and technical editors Andrea Boucherand Greg Guntle We thank them for all their hard work on this book
Trang 33the folks at Waterside Productions for being our agents.
A special thank you to Bill Ramos, Tim Getsch, and the Microsoft Access Team
We would be remiss if we do not thank several people at Microsoft, especially BillRamos, Microsoft Access and Excel Product Manager He was incredibly helpful insupplying us with beta builds and information not easily available He kept usinformed about last minute changes and sent us new CDs when our examples didn’twork When a few more things didn’t work near the end of the beta, Tim Getschworked with us to understand the last-minute changes A special thank you goes toSanjay Jacob, who supplied us with a copy of the Access Developers Edition andspent time teaching us the new features before beta release so that we could finishthe last chapter of our book on time To John Sigler, Group Product Manager, forhis support through his people and his recognition of our ideas at a recent confer-ence While this is much appreciated, beating Cary at golf is unforgivable Nexttime
Thanks to these wonderful people, we were able to deliver a quality book to ourreaders
— Cary Prague, Michael R Irwin, and Jennifer Reardon
To my family — Karen, David, Jeff (Tall man), and Alex (Turtle) — whom I ignore waytoo much Finally, to the people of Database Creations who let me miss all of mydeadlines while I worked on this book To Kim, Larry, Diana, Julie, Phuc, Steve, Bill,Debbie, Radic, Karen, and especially Dick James for handling all my technical sup-port calls
— JR
Trang 34Preface xiAcknowledgments xxxi
Part I: Creating Desktop Applications 1 Section I: Working with Data Tables and Queries 1
Chapter 1: Understanding Data 3Chapter 2: Creating and Building Tables 35Chapter 3: Entering Data into Tables and Forms 85Chapter 4: Creating and Understanding Relationships 123Chapter 5: Displaying Selected Data with Queries 153Chapter 6: Using Operators and Expressions in Multi-table Select Queries 203Chapter 7: Working with External Data 247
Section II: Building Forms and Reports 299
Chapter 8: Understanding the Many Uses of Forms and Controls 301Chapter 9: Building and Manipulating Forms and Controls 321Chapter 10: Creating Bound Forms and Placing Controls 349Chapter 11: Adding Data-Validation Features to Forms 391Chapter 12: Creating Professional-Looking Forms and Reports 421Chapter 13: Understanding and Creating Reports 443Chapter 14: Working with Subforms 503Chapter 15: Creating Calculations and Summaries in Reports 539Chapter 16: Presenting Data with Special Report Types 575Chapter 17: Using OLE Objects, Graphs, Pivot Tables/Charts, and
ActiveX Controls 603
Section III: Automating Your Applications 653
Chapter 18: Understanding Visual Basic and the VBA Editor 655Chapter 19: Introduction to Programming and Events 679Chapter 20: Working with Expressions and Functions 713Chapter 21: Working with SQL, Recordsets, and ADO 737Chapter 22: Automating, Searches, Filters, and Query Parameters 757Chapter 23: Calling Subprocedures and Functions 771Chapter 24: Effective Debugging and Error Handling in VBA 783
Trang 35Part II: Creating Enterprise Applications 883 Section IV: Upsizing to SQL Server and MSDE 2000 883
Chapter 27: Upsizing Data to a SQL Server Database 885Chapter 28: Working with Access Projects 903Chapter 29: Working with Access Projects and SQL Server Tables
and Queries 921
Part III: Creating Web Applications 945 Section V: Creating Data Access Pages and Using XML
and InfoPath 945
Chapter 30: Using and Creating Access Objects for Intranets
and the Internet 947Chapter 31: Building and Working with Data Access Pages 981Chapter 32: XML, Access, and InfoPath 1037
Part IV: Advanced Access Database Topics 1081
Chapter 33: Exchanging Data with Office Applications 1083Chapter 34: Adding Security to Applications 1101Chapter 35: Creating Help Systems 1143Chapter 36: Working with Advanced Select Queries and
Other Query Topics 1179Chapter 37: Working with Action and SQL Queries 1229Chapter 38: Increasing the Speed of an Application 1265Chapter 39: Preparing Your Application for Distribution 1309
Part V: Appendixes and Reference Material 1331
Appendix A: Access 2003 Specifications 1333Appendix B: Access Auto Auction Tables 1339Appendix C: Using the CD-ROM Included with the Book 1345Appendix D: Using Standard Naming Conventions 1355
Index 1363
Trang 36Preface xi Acknowledgments xxxi
Part I: Creating Desktop Applications 1 Section I: Working with Data Tables and Queries 1
Chapter 1: Understanding Data 3
The Database Terminology of Access 4What is a database? 4Databases, tables, records, fields, and values 5Using More Than One Table 7Working with multiple tables 8Why you should create multiple tables 8Access Database Objects and Views 9Datasheets 9Queries and dynasets 10Data-entry and display forms 10Reports 11Designing the system’s objects 11The Seven-Step Design Method 12Step 1: The overall design — From concept to reality 13Step 2: Report design — Placing your fields 15Step 3: Data design — What fields do you have? 17Step 4: Table design and relationships 24Step 5: Field design data-entry rules and validation 27Step 6: Form design — Input 30Step 7: Automation design — Menus 32
Chapter 2: Creating and Building Tables 35
Creating Database Tables 35Creating a Database 35Templates Section 37Blank database 39The Database Window 41Objects menu bar 42Groups menu bar 43The Database window toolbar buttons 44The Access window toolbar 44
Trang 37The table design process 46The New Table dialog box 47Creating a new table with a Datasheet View 49The Table Design Window 51Using the Table Design window toolbar 52Working with fields 52Creating the tblContacts Table 56AutoNumber fields and Access 56Completing the tblContacts Table 57Changing a Table Design 59Inserting a new field 59Deleting a field 59Changing a field location 60Changing a field name 60Changing a field size 60Changing a field data type 61Understanding Field Properties 62Entering field-size properties 64Using formats 65Entering formats 69Entering input masks 70The Input Mask Wizard 72Entering decimal places 73Creating a caption 73Setting a default value 73Working with validation 73Understanding the Lookup Property window 76Determining the Primary Key 76Creating a unique key 77Creating the primary key 78The Indexes window 78The Table Properties window 79Printing a Table Design 80Saving the Completed Table 81Manipulating Tables in a Database Window 81Renaming tables 81Deleting tables 82Copying tables in a database 82Copying a table to another database 83Adding Records to a Database Table 83
Chapter 3: Entering Data into Tables and Forms 85
Understanding Datasheets 85The Datasheet Window 86Moving within a datasheet 88The Navigation buttons 88The Datasheet toolbar 89
Trang 38Opening a Datasheet 92
Entering New Data 92
Saving the record 94
Understanding automatic data-type validation 95
Understanding how properties affect data entry 96
Navigating Records in a Datasheet 98
Moving between records 98
Finding a specific value 99
Changing Values in a Datasheet 102
Replacing an existing value manually 102
Changing an existing value 103
Fields that you can’t edit 104
Using the Undo Feature 104
Copying and Pasting Values 105
Replacing Values 105
Adding New Records 106
Deleting Records 107
Adding, Changing, and Deleting Columns 107
Deleting a column from a datasheet 108
Adding a column to a datasheet 108
Changing a field name (column header) 108
Displaying Records 108
Changing the field order 108
Changing the field display width 110
Changing the record display height 111
Displaying cell gridlines 112
Changing display fonts 113
Hiding and unhiding columns 114
Freezing columns 115
Saving the changed layout 115
Saving a record 115
Sorting and Filtering Records in a Datasheet 115
Using the QuickSort feature 116
Using Filter By Selection 116
Using Filter By Form 118
Printing Records 118
Printing the datasheet 119
Using the Print Preview window 119
Chapter 4: Creating and Understanding Relationships 123
Tables Used in the Access Auto Auctions Database 123
Understanding Keys 126
Deciding on a primary key 128
Benefits of a primary key 129
Creating a primary key 130
Understanding foreign keys 132
Understanding Relations between Tables 132
A review of relationships 133
Understanding the four types of table relationships 133
Trang 39Creating Relationships 136Using the Relationships window 137Creating relationships between tables 139Specifying relationship options in the
Edit Relationships dialog box 140Finishing the relationships between the tables
of the Access Auto Auctions system 144Saving the relationships between tables 146Adding another relationship 146Deleting an existing relationship 147Join lines in the Relationships window 147Printing a report of the relationships 147Using Subdatasheets 148Setting up sub-datasheets 149
Chapter 5: Displaying Selected Data with Queries 153
Understanding Queries 153What is a query? 154Types of queries 156Query capabilities 157How dynasets work 158Creating a Query 158Selecting a table 159Using the Query window 161Navigating the Query Design window 161Using the Query Design toolbar 162Using the QBE pane of the Query Design window 163Selecting Fields 163Adding a single field 163Adding multiple fields 165Adding all table fields 166Displaying the Dynaset 167Working with the datasheet 168Changing data in the query datasheet 168Returning to the query design 168Working with Fields 168Selecting a field 168Changing field order 170Resizing columns in design mode 170Removing a field 171Inserting a field 171Changing the field display name 171Showing table names 172Showing a field 173Changing the Sort Order 173Specifying a sort 174
Trang 40Displaying Only Selected Records 175
Understanding record criteria 175
Entering simple character criteria 176
Entering other simple criteria 177
Printing a Query Dynaset 178
Saving a Query 179
Adding More than One Table to a Query 180
Working with the Table/Query Pane 181
The join line 181
Resizing the Table/Query pane 182
Manipulating the Field List window 184
Moving a table 184
Removing a table 184
Adding more tables 185
Resizing a Field List window 185
Adding Fields from More than One Table 185
Adding a single field 185
Viewing the table names 186
Adding multiple fields at the same time 186
Adding all table fields 187
Understanding the Limitations of Multiple-Table Queries 188
Updating limitations 188
Overcoming query limitations 190
Creating and Working with Query Joins 191
Joining tables 192
Specify the type of join 193
Deleting joins 194
Understanding Types of Table Joins 195
Inner joins (Equi-joins) 195
Changing join properties 196
Inner and outer joins 198
Creating a Cartesian product 201
Chapter 6: Using Operators and Expressions
in Multi-table Select Queries 203
What Are Operators? 203
Moving beyond Simple Queries 219
Using query comparison operators 220
Understanding complex criteria selection 222
Using functions in select queries 225
Referencing fields in select queries 226