You are on page 1of 260

Version 4.

Base Handbook

Copyright
This document is Copyright 2013 by its contributors as listed below. You may distribute it and/or modi y it under the terms o either the !"# !eneral $ublic %icense &http'//www.gnu.org/licenses/gpl.html() *ersion 3 or later) or the Creati*e Commons +ttribution %icense &http'//creati*ecommons.org/licenses/by/3.0/() *ersion 3.0 or later. +ll trademar,s within this guide belong to their legitimate owners.

Contributors
-ochen .chi ers /a0el 1ussman 2an %ewis 1obert !ro3,op 4artin 5o6 -ean /ollis 7eber -ost %ange +ndrew $itonya,

Acknowledgments
This boo, is based on an original !erman document) which was translated by /a0el 1ussman and 4artin 5o6.

Feedback
$lease direct any comments or suggestions about this document to' documentation8global.libreo ice.org

Publication date and software version


$ublished 3 -uly 2013. 9ased on %ibre: ice 4.0.

Documentation for LibreOffice is available at http://www.libreoffice.org/get-help/documentation

Contents
Copyright..................................................................................................................................... 2 Contributors............................................................................................................................. 2 5eedbac,................................................................................................................................ 2 +c,nowledgments................................................................................................................... 2 $ublication date and so tware *ersion..................................................................................... 2

Preface.................................................................................................................................. 7
7ho is this boo, or;................................................................................................................... < 7hat=s in this boo,;..................................................................................................................... < 7here to get more help............................................................................................................... < /elp system............................................................................................................................ < 5ree online support................................................................................................................. < $aid support and training........................................................................................................ > 7hat you see may be di erent.................................................................................................... > ?llustrations.............................................................................................................................. > ?cons..................................................................................................................................... 10 #sing %ibre: ice on a 4ac........................................................................................................ 10 7hat are all these things called;............................................................................................... 10 7ho wrote this boo,;................................................................................................................. 11 5re@uently as,ed @uestions....................................................................................................... 12

Chapter 1 Introduction to ase.......................................................................................................... 1!


?ntroduction................................................................................................................................ 14 9ase A a container or database content....................................................................................14 2ata input using orms............................................................................................................... 1B 2ata input directly into a table.................................................................................................... 1C Dueries A getting in ormation on data in tables.......................................................................... 1E 1eports A presentation o data................................................................................................... 1E

Chapter " Creating a #atabase..........................................................................................................."1


!eneral notes on the creation o a database............................................................................. 22 "ew database using the internal /.D% engine.......................................................................... 22 +ccessing e6ternal databases................................................................................................... 22 4y.D% databases..................................................................................................................... 23 d9ase databases....................................................................................................................... 30 .preadsheets............................................................................................................................. 31 Thunderbird address boo,......................................................................................................... 32

Chapter ! $ables.................................................................................................................................. !!
!eneral in ormation on tables.................................................................................................... 34 1elationships between tables.................................................................................................... 34 1elationships or tables in databases.................................................................................... 34 Tables and relationships or the e6ample database............................................................... 3E Creating tables........................................................................................................................... 40 Creation using the graphical user inter ace........................................................................... 41 2irect entry o .D% commands............................................................................................. 43
Base Handbook

%in,ing tables............................................................................................................................. 4< Fntering data into tables............................................................................................................ B2 Fntry using the 9ase !#?...................................................................................................... B2 2irect entry using .D%.......................................................................................................... BE $roblems with these data entry methods...............................................................................B>

Chapter % Forms.................................................................................................................................. &1


5orms ma,e data entry easier................................................................................................... C2 Creating orms........................................................................................................................... C2 + simple orm........................................................................................................................ C2 Toolbars or orm design........................................................................................................ C3 5orm properties......................................................................................................................... CC $roperties o controls............................................................................................................ C> + simple orm completed....................................................................................................... >B 4ain orms and sub orms........................................................................................................ 103 :ne *iew A many orms........................................................................................................... 11B

Chapter ' (ueries.............................................................................................................................. 1"1


!eneral in ormation on @ueries................................................................................................ 122 Fntering @ueries....................................................................................................................... 122 Creating @ueries using the Duery 2esign dialog................................................................. 122 Duery enhancement using .D% 4ode................................................................................ 134 #sing an alias in a @uery.......................................................................................................... 141 Dueries or the creation o list bo6 ields.................................................................................. 142 Dueries as a basis or additional in ormation in orms.............................................................. 143 2ata entry possibilities within @ueries...................................................................................... 143 #se o parameters in @ueries................................................................................................... 144 .ub@ueries............................................................................................................................... 144 Correlated sub@ueries.............................................................................................................. 14B Dueries as source tables or @ueries....................................................................................... 14B .ummari0ing data with @ueries................................................................................................ 14C 4ore rapid access to @ueries using table *iews....................................................................... 14E

Chapter & )eports..............................................................................................................................1%*


Creating reports using the 1eport 9uilder................................................................................ 1B0 The user inter ace o the 1eport 9uilder.................................................................................. 1B0 !eneral properties o ields................................................................................................. 1BE 2ata properties o ields...................................................................................................... 1C1 5unctions in the 1eport 9uilder................................................................................................ 1C2 Fntering ormulas................................................................................................................ 1C2 #serGde ined unctions........................................................................................................ 1C< 5ormula entry or a ield...................................................................................................... 1C> Conditional print.................................................................................................................. 1C> Conditional ormatting......................................................................................................... 1C>

Chapter 7 +inking to #atabases....................................................................................................... 171


!eneral notes on database lin,age......................................................................................... 1E2
! Base Handbook

1egistration o databases........................................................................................................ 1E2 2ata source browser................................................................................................................ 1E2 2ata to Te6t......................................................................................................................... 1E4 2ata to 5ields...................................................................................................................... 1EE 4ail merge............................................................................................................................... 1E< 2ata source o current document........................................................................................ 1E< F6plorer on/o ..................................................................................................................... 1E< Creating mail merge documents.............................................................................................. 1E< %abel printing........................................................................................................................... 1<B 2irect creation o mail merge and label documents................................................................. 1<< 4ail merge using the mouse............................................................................................... 1<< Creating orm letters by selecting ields............................................................................... 1<> F6ternal orms.......................................................................................................................... 1>0 2atabase use in Calc............................................................................................................... 1>1 Fntering data into Calc........................................................................................................ 1>1 F6porting data rom Calc into a database............................................................................ 1>3 Con*erting data rom one database to another........................................................................ 1>C

Chapter , #atabase tasks................................................................................................................. 1*7


!eneral remar,s on database tas,s........................................................................................ 1>< 2ata iltering............................................................................................................................. 1>< .earching or data................................................................................................................... 200 Code snippets.......................................................................................................................... 201 !etting someone=s current age........................................................................................... 201 !etting a running balance by categories............................................................................. 202 %ine numbering................................................................................................................... 203 !etting a line brea, through a @uery................................................................................... 20B !rouping and summari0ing................................................................................................. 20B

Chapter * -acros...............................................................................................................................".7
!eneral remar,s on macros.................................................................................................... 20< ?mpro*ing usability................................................................................................................... 20> +utomatic updating o orms................................................................................................ 20> 5iltering records.................................................................................................................. 210 .earching data records....................................................................................................... 213 Combobo6es as listbo6es with an entry option.................................................................... 21B "a*igation rom one orm to another................................................................................... 22B 1emo*ing distracting elements rom orms......................................................................... 22C 2atabase tas,s e6panded using macros................................................................................. 22C 4a,ing a connection to a database..................................................................................... 22C .ecuring your database...................................................................................................... 22E 2atabase compaction.......................................................................................................... 22< 2ecreasing the table inde6 or auto*alue ields................................................................... 22< 2ialogs..................................................................................................................................... 22>

Chapter 1. #atabase -aintenance.................................................................................................... "!*


!eneral remar,s on maintaining databases............................................................................. 240 Compacting a database........................................................................................................... 240 1esetting auto*alues............................................................................................................... 240
Base Handbook "

Duerying database properties.................................................................................................. 240 Testing tables or unnecessary entries..................................................................................... 241 Testing entries using relationship de inition......................................................................... 241 Fditing entries using orms and sub orms............................................................................ 242 Dueries or inding orphan entries....................................................................................... 243 2atabase search speed........................................................................................................... 243 F ect o @ueries.................................................................................................................. 243 F ect o listbo6es and combobo6es.................................................................................... 244

Appendi/ ......................................................................................................................... "%'


9arcodes................................................................................................................................. 24C 2ata types or the table editor.................................................................................................. 24C ?ntegers............................................................................................................................... 24C 5loatingGpoint numbers........................................................................................................ 24C Te6t..................................................................................................................................... 24E Time.................................................................................................................................... 24E :ther................................................................................................................................... 24E 9uiltGin unctions and stored procedures.................................................................................. 24< "umeric............................................................................................................................... 24< Te6t..................................................................................................................................... 24> 2ate/Time............................................................................................................................ 2B0 2atabase connection........................................................................................................... 2B1 .ystem................................................................................................................................ 2B1 ?n ormation tables or /.D%29................................................................................................ 2B2 2atabase repair or H.odb iles.................................................................................................. 2B3 Connecting a database to an e6ternal /.D%29...................................................................... 2BB Changing the database connection to e6ternal /.D%29........................................................2BE Changing the database connection or multiGuser access...................................................2BE +utoGincrementing *alues with e6ternal /.D%29............................................................... 2B>

Base Handbook

$reface

0ho is this book for1


+nyone who wants to get up to speed @uic,ly with %ibre: ice 9ase will ind this boo, *aluable. You may wish to irst read Chapter <) !etting .tarted with 9ase) in the %etting &tarted guide.

0hat2s in this book1


This boo, introduces 9ase) the database component o %ibre: ice. 9ase uses the /.D%29 database engine to create database documents. ?t can access databases created by many database programs) including 4icroso t +ccess) 4y.D%) :racle) and $ostgre.D%. 9ase includes additional unctionality that allows you to create ull dataGdri*en applications. This boo, introduces the eatures and unctions o 9ase) using two e6ample databases.

Creating a database +ccessing e6ternal databases Creating and using tables in relational databases Creating and using orms or data entry #sing @ueries to bring together data rom di erent tables) calculate results where necessary) and @uic,ly ilter a speci ic record rom a mass o data Creating reports using the 1eport 9uilder %in,ing databases to other documents and e6ternal orms) including use in mail merge 5iltering and searching data #sing macros to pre*ent input errors) simpli y tas,s) and impro*e usability o orms 4aintaining databases

0here to get more help


This boo,) the other %ibre: ice user guides) the builtGin /elp system) and user support systems assume that you are amiliar with your computer and basic unctions such as starting a program) opening and sa*ing iles.

3elp system
%ibre: ice comes with an e6tensi*e /elp system. This is your irst line o support or using %ibre: ice. To display the ull /elp system) press '( or select +ibre4ffice 3elp rom the /elp menu. ?n addition) you can choose whether to acti*ate Tips) F6tended Tips) and the /elp +gent &using $ools 5 4ptions 5 +ibre4ffice 5 6eneral(. ? Tips are enabled) place the mouse pointer o*er any o the icons to see a small bo6 &ItooltipJ( with a brie e6planation o the iconKs unction. 5or a more detailed e6planation) select 3elp 5 0hat2s $his1 and hold the pointer o*er the icon.

Free online support


The %ibre: ice community not only de*elops so tware) but pro*ides ree) *olunteerGbased support. .ee Table 1 and this web page' http'//www.libreo ice.org/getGhelp/ You can get comprehensi*e online support rom the community through mailing lists and the +s, %ibre: ice website. :ther websites run by users also o er ree tips and tutorials. This orum pro*ides community support or %ibre: ice' http'//en.libreo ice orum.org/

Base Handbook

This site pro*ides support or %ibre: ice) among other programs' http'// orum.openo ice.org/en/ orum/ *able (: 'ree support for LibreOffice users Free LibreOffice support
+s, %ibre: ice 2ocumentation 5+Ds 4ailing lists Duestions and answers rom the %ibre: ice community http'//as,.libreo ice.org/en/@uestions/ #ser guides) howGtos) and other documentation. http'//www.libreo ice.org/getGhelp/documentation/ https'//wi,i.document oundation.org/2ocumentation/$ublications +nswers to re@uently as,ed @uestions http'//wi,i.document oundation.org/5a@ 5ree community support is pro*ided by a networ, o e6perienced users http'//www.libreo ice.org/getGhelp/mailingGlists/ The %ibre: ice website in your language. http'//www.libreo ice.org/internationalGsites/ ?nternational mailing lists http'//wi,i.document oundation.org/%ocalL4ailingL%ists ?n ormation about a*ailable accessibility options. http'//www.libreo ice.org/getGhelp/accessibility/

?nternational support

+ccessibility options

Paid support and training


+lternati*ely) you can pay or support ser*ices. .er*ice contracts can be purchased rom a *endor or consulting irm speciali0ing in %ibre: ice.

0hat you see may be different


Illustrations
%ibre: ice runs on 7indows) %inu6) and 4ac :. M operating systems) each o which has se*eral *ersions and can be customi0ed by users & onts) colors) themes) window managers(. The illustrations in this guide were ta,en rom a *ariety o computers and operating systems. There ore) some illustrations will not loo, e6actly li,e what you see on your computer display. +lso) some o the dialogs may be di er because o the settings selected in %ibre: ice. You can either use dialogs rom your computer system &de ault( or dialogs pro*ided by %ibre: ice. To change to using %ibre: ice dialogs' 1( :n %inu6 and 7indows operating systems) go to $ools 5 4ptions 5+ibre4ffice 5 6eneral on the main menu bar to open the dialog or general options. 2( :n a 4ac operating system) go to +ibre4ffice 5 Preferences 5 6eneral on the main menu bar to open the dialog or general options. 3( .elect +se LibreOffice dialogs in Open/&ave dialogs and) in %inu6 and 4ac :. M operating systems only) $rint dialogs to display the %ibre: ice dialogs on your computer display. 4( Clic, 47 to sa*e your settings and close the dialog.

$reface

Icons
The icons used to illustrate some o the many tools a*ailable in %ibre: ice may di er rom the ones used in this guide. The icons in this guide ha*e been ta,en rom a %ibre: ice installation that has been set to display the !ala6y set o icons. ? you wish) you can change your %ibre: ice so tware pac,age to display !ala6y icons as ollows' 1( :n %inu6 and 7indows operating systems) go to $ools 5 4ptions 5+ibre4ffice 5 8iew on the main menu bar to open the dialog or *iew options. 2( :n a 4ac operating system) go to +ibre4ffice 5 Preferences 5 8iew on the main menu bar to open the dialog or *iew options. 3( ?n +ser interface - .con si/e and st0le select %ala10 rom the options a*ailable in the dropG down list. 4( Clic, 47 to sa*e your settings and close the dialog.
.ome %inu6 operating systems) or e6ample #buntu) include %ibre: ice as part o the installation and may not include the !ala6y set o icons. You should be able to download the !ala6y icon set rom the so tware repository or your %inu6 operating system.

9ote

:sing +ibre4ffice on a -ac


.ome ,eystro,es and menu items are di erent on a 4ac rom those used in 7indows and %inu6. The table below gi*es some common substitutions or the instructions in this chapter. 5or a more detailed list) see the application /elp. Windows or Linux
$ools 5 4ptions menu selection 2ight-click 3trl 53ontrol6 '" '((

Mac equivalent
+ibre4ffice 5 Preferences 3ontrol4click and/or right-click depending on computer setup z 53ommand6 &hiftNzN'" zN*

Effect
+ccess setup options :pen a conte6t menu #sed with other ,eys :pen the "a*igator :pen the .tyles and 5ormatting window

0hat are all these things called1


The terms used in %ibre: ice or most parts o the user interface &the parts o the program you see and use) in contrast to the behindGtheGscenes code that actually ma,es it wor,( are the same as or most other programs. + dialog is a special type o window. ?ts purpose is to in orm you o something) or re@uest input rom you) or both. ?t pro*ides controls or you to use to speci y how to carry out an action. The technical names or common controls are shown in 5igure 1. ?n most cases we do not use the technical terms in this boo,) but it is use ul to ,now them because the /elp and other sources o in ormation o ten use them.

(7

Base Handbook

'igure (: Dialog showing common controls 1( 2( 3( 4( Tabbed page &not strictly spea,ing a control(. 1adio buttons &only one can be selected at a time(. Chec,bo6 &more than one can be selected at a time(. .pin bo6 &clic, the up and down arrows to change the number shown in the te6t bo6 ne6t to it) or type in the te6t bo6(. B( Thumbnail or pre*iew. C( 2ropGdown list rom which to select an item. E( $ush buttons. ?n most cases) you can interact only with the dialog &not the document itsel ( as long as the dialog remains open. 7hen you close the dialog a ter use &usually) clic,ing 47 or another button sa*es your changes and closes the dialog() then you can again wor, with your document. .ome dialogs can be le t open as you wor,) so you can switch bac, and orth between the dialog and your document. +n e6ample o this type is the 5ind O 1eplace dialog.

0ho wrote this book1


This boo, was written by *olunteers rom the %ibre: ice community. $ro its rom sales o the printed edition will be used to bene it the community.

$reface

((

Fre;uently asked ;uestions


3ow is +ibre4ffice licensed1 %ibre: ice is distributed under the :pen .ource ?nitiati*e &:.?( appro*ed %esser !eneral $ublic %icense &%!$%(. The %!$% license is a*ailable rom the %ibre: ice website' http'//www.libreo ice.org/download/license/ -ay I distribute +ibre4ffice to anyone1 Yes. 3ow many computers may I install it on1 +s many as you li,e. -ay I sell it1 Yes. -ay I use +ibre4ffice in my business1 Yes. Is +ibre4ffice available in my language1 %ibre: ice has been translated &locali0ed( into o*er 40 languages) so your language probably is supported. +dditionally) there are o*er E0 spelling) h0phenation) and thesaurus dictionaries a*ailable or languages) and dialects that do not ha*e a locali0ed program inter ace. The dictionaries are a*ailable rom the %ibre: ice website at' www.libreo ice.org. 3ow can you make it for free1 %ibre: ice is de*eloped and maintained by *olunteers and has the bac,ing o se*eral organi0ations. I am writing a software application. -ay I use programming code from +ibre4ffice in my program1 You may) within the parameters set in the %!$%. 1ead the license' http'//www.libreo ice.org/download/license/ 0hy do I need <ava to run +ibre4ffice1 Is it written in <ava1 %ibre: ice is not written in -a*aP it is written in the CNN language. -a*a is one o se*eral languages that can be used to e6tend the so tware. The -a*a -2Q/-1F is only re@uired or some eaturesP the most notable one is the /.D%29 relational database engine. 3ow can I contribute to +ibre4ffice1 You can help with the de*elopment and user support o %ibre: ice in many ways) and you do not need to be a programmer. To start) chec, out this webpage' http'//www.document oundation.org/contribution/ -ay I distribute the P#F of this book= or print and sell copies1 Yes) as long as you meet the re@uirements o one o the licenses in the copyright statement at the beginning o this boo,. You do not ha*e to re@uest special permission. ?n addition) we re@uest that you share with the proRect some o the pro its you ma,e rom sales o boo,s) in consideration o all the wor, we ha*e put into producing them.

(8

Base Handbook

3hapter ( .ntroduction to Base

Introduction
?n e*eryday o ice operation) spreadsheets are regularly used to aggregate sets o data and to per orm some ,ind o analyses on them. +s the data in a spreadsheet is laid out in a table *iew) plainly *isible and able to be edited or added to) many users as, why they should use a database instead o a spreadsheet. This handboo, e6plains the di erences between the two) beginning with a short section on what can be done with a database. This chapter introduces two database e6amples and the entire /andboo, is built around these. :ne database is named Media_without_macros.odb and the other) e6tended with the inclusion o macros) is named Media_with_macros.odb.

ase > a container for database content


+ 9ase ile is a compressed older that contains in ormation or the di erent wor, areas o 9ase. ?n daily use) 9ase initially opens with the ollowing *iew.

The 9ase en*ironment contains our wor, areas' Tables) Dueries) 5orms) and 1eports. 2epending on the wor, area selected) *arious tas,sScreating new content or calling up e6isting elementsS may be carried out. 9ase starts with the 5orm *iew) because orms are the elements most commonly used when wor,ing with databases.

(!

Base Handbook

#ata input using forms


.imple orms show Rust one table as in the upper part o the Loan orm.

The %oan orm has been e6tended to show additional in ormation'

T T T T

The range o persons shown can be iltered on last name to limit the detail shown. ? a user inputs the letter I!J in the 5ilter &%ast "ame( ield at the right o the %oan table) only persons whose last name begins with I!J will be shown. "ew borrower in ormation can be input directly into the table ields o the orm. 2etails o items to be borrowed are input and shown in the area in the middle o the orm. ? a pre*iously borrowed item is o*erdue and must be returned this area is bloc,ed &no input possible( and the title will indicate I%oan temporary loc,edUJ. ?tems on loan are shown in the lower area o the orm. The date or returning each borrowed item is compared with the current date and the remaining loan duration shown.

3hapter ( .ntroduction to Base

("

T T T

The borrowing date is set as the current date. ?n the pullGdown ield at the right o the %oan 2ate are the media items which can be borrowed. ?tems which are already on loan to the selected borrower are not a*ailable or selection. 4edia items selected or loan are added to the current loan details by clic,ing the )efresh button. ?n the lower section o the orm &1eturn( it is not possible to delete a data row. :nly the ields 1eturn 2ate and F6tension can be edited. ? a borrower was pre*iously loc,ed and has subse@uently returned the o*erdue item&s() the lending area can be unloc,ed by clic,ing the )efresh button.

+ll these unctions can be carried out without using macros) when the orm is set up and illed in the manner described.

#ata input directly into a table

The table structure or such a orm is relati*ely basic and easy to set up. ?n the table shown abo*e) the same data can be directly input in the rows and columns o the table as when using the orm.

The irst ield shows a primary ,ey &I?2J( which is automatically generated. 4ore on this
topic can be ound in the chapter on Tables.

The second ield) 4ediaL?2) stores the primary ,ey o the 4edia table) a number which
re ers to the 4edia. ?n the orm the media id) title and author are shown in the dropGdown menu.

(#

Base Handbook

The third ield) 1eaderL?2) stores the primary ,ey o the 1eader table. This ,ey is a number
which re ers to the reader. ?n the orm the %ast name and 5irst name o the reader are shown.

The ourth ield stores the loan date. ? this date is present and is later than the current
date) the corresponding data set or the reader is shown in the bottom table o the orm under 1eturn.

The ield mar,ed F6tension contains in ormation about e6tensions o the loan or an item.
The meaning o the *alues 1) 2 and so on is e6plained later. The database contains a special table called .ettings or this type o in ormation. The input o this data permits the management o a simple library.

(ueries > getting information on data in tables

The @uery shown abo*e lists all media which are currently out on loan. ?t calculates or each item how long it has been on loan and the balance o the loan period.

+ll media or which the 1eturnL2ate ield is empty is listed. +s an additional o*er*iew) the
medium name is included in the @uery together with the 4ediaL?2.

The re erence to the 1eader is established with the primary ,ey o the 1eader table. The *alue o the %oan2ays ield is calculated as the di erence between the %oanL2ate and
the current date.

The number o %oan2ays is subtracted rom the %oan Time to gi*e the remaining number
o days in the loan period. The %oan Time can *ary with di erent media types.

?n the .ettings table a *alue o =1= or F6tension corresponds to an e6tension o the loan
period o E days. ?n the data set abo*e) the line with 4ediaL?2 =2= shows an e6tension o E days.

)eports > presentation of data


9e ore an actual report in the orm o a recall notice can be printed) the recall in ormation must be entered into the 1ecall orm. The table in the orm shows all persons who ha*e borrowed items with a negati*e remaining loan time. 5or each media item to be recalled) the recall date and recall notice number is entered. The recall date de aults to the current date. The recall number is an integer incremented by 1 with each successi*e recall notice or a particular lender/media.
3hapter ( .ntroduction to Base (9

This orm) in the current database e6ample without macros) re@uires user input to create recall notices. ?n the macro *ersion) the date is automatically entered and the recall notice printed.

The recall notice is generated by means o a @uery rom the pre*iously input data. The user o the database needs only to choose the 1ecall report and a recall letter can be printed out and sent to all persons who ha*e a recall entry made in the orm on the pre*ious page. ?n such a report there may be multiple entries &o*erdue items( or a particular person. ? the table containing the items or this person e6ceeds the space on a page) it is e6tended to co*er a succeeding page. .uch a report is more encompassing than a mail merge letter produced with 7riter. ?t automatically gathers together the data sets or printing and arranges the necessary accompanying te6t accordingly.

()

Base Handbook

3hapter ( .ntroduction to Base

(,

3hapter 8 3reating a Database


How to create a new database

6eneral notes on the creation of a database


The basics o creating a database in %ibre: ice are described in Chapter < o the %etting &tarted guide) !etting .tarted with 9ase. The database component o %ibre: ice) called 9ase) pro*ides a graphical inter ace or wor,ing with databases. ?n addition) %ibre: ice contains a *ersion o the /.D% database engine. This /.D%29 database can only be used by a single user. The entire data set is stored in an :29 ile which has no ile loc,ing mechanism when opened by a user.

9ew database using the internal 3?(+ engine


? a database with multiple users is not planned) or the user wishes to gain some initial e6perience with a database) the internal database engine will su ice. ?t is possible at some later stage to trans er the database to an e6ternal /.D%29 en*ironment) where multiple users can ha*e concurrent access to the database on the /.D%29 ser*er. This is described in the +ppendi6 to this /andboo,. The creation o a new internal database is described in detail in !etting .tarted with 9ase. + database which is registered in %ibre: ice can be accessed by other program components as a data source & or e6ample) mail merge(. This registration process can be carried out at a later stage i desired.

Accessing e/ternal databases


+n e6ternal database must e6ist be ore it can be accessed. +ssuming that access to a database is desired) the database must be set up to allow networ, connections with a speci ic user name and password be ore e6ternal programs can connect to it. 7hen such a database is properly set up) a user may) depending on the a*ailable connection so tware &the database dri*er() create tables) input data) and @uery data. Clic, on File 5 9ew 5 #atabase to open the 2atabase 7i0ard and allow a connection to an e6isting database to be made. The list o a*ailable database types *aries according to operating system and user inter ace) but the ollowing should always be a*ailable'

T T T T T T T T T

d9ase -29C 4y.D% :29C :racle -29C $ostgre.D% .preadsheet Te6t as well as *arious types o address boo,s.

The connection options will *ary according to the type o database selected. These can in any case be corrected later) a ter the H.odb ile is created. .ome database types & or e6ample spreadsheets( do not allow new data to be entered. These are used only to search or or report on e6isting data.

88

Base Handbook

-y?(+ databases
There was an e6tension or 4y.D%) the 4y.D% "ati*e Connector) which should allow 9ase to connect directly to a 4y.D% database. The e6tension was in the %ibre: ice F6tensions center under the 9ase Category but is not being de*eloped at present. !eneral access to 4y.D% or *ersions o %ibre: ice rom 3.B onwads is *ia -29C or :29C. To be able to use -29C) it is necessary to install mys@lGconnectorGRa*a.Rar. This -a*a +rchi*e ile is best copied into the same older where the current Ra*a *ersion used in %ibre: ice is located. This is li,ely to be a sub older li,e ...javapath.../lib/ext or a %inu6 installation. +lternati*ely the appropriate older containing the -a*a archi*e can be set through $ools 5 4ptions 5 <ava 5 ClassPath. The method o access to an e6isting 4y.D% database is shown in the ollowing steps.

Creation o a new database is only possible in the internal /.D%29 ormat. Connection to an e6ternal database is only possible when the database already e6ists. .elect the 3onnect to an e1isting database option. + list o database ormats is contained on the pullGdown menu. .elect 4y.D%.

3hapter 8 3reating a Database

Connection to 4y.D% can be *ia :29C or -29C unless a nati*e 4y.D% connector has been installed. ?n this case a direct connection to 4y.D% is possible. ?n this e6ample) select the -a*a connector -29C.

The database name must be ,nown and input. ? the 4y.D% ser*er is on the same computer as %ibre: ice) then the .er*er name can be set as localhost. :therwise the ?$ address o the ser*er or its hostname on the networ, or internet must be input. ?t is also possible to access a database with 9ase where the database is located on the website o an ?nternet .er*ice $ro*ider. The de ault port number will usually be correct.

8!

Base Handbook

Type in the -29C dri*er class and clic, the $est class button. + dialog should pop up con irming that the connector is loaded and accessible using -a*a. The mys@lGconnectorGRa*a.Rar ile must either be in the same path as the *ersion o -a*a in use in %ibre: ice or directly lin,ed in to %ibre: ice.

3hapter 8 3reating a Database

8"

The database on the networ, should be protected with a user name and password. +gain a connection test may be carried out.
? a direct connection was selected) this test will generate error messages. 7ithout testing) 9ase will) at the end o the +ssistant) open the database window and connection to 4y.D%.

9ote

8#

Base Handbook

The connection test starts the authentication process using the user name pre*iously input. + ter the correct password is input) a dialog announces the result o the test. ? 4y.D% is not running at this time) an error message is shown.

The inal step is registering the database. The database can) i necessary) be registered at a later time to allow its use with 7riter or Calc.

3hapter 8 3reating a Database

89

The +ssistant ends the connection process with the storage o the :29 database. The :29 database contains all the connection in ormation needed to allow tables in the database to be accessed whene*er the database is opened. +t this stage choose a name or the :29 database ile and sa*e it. The ne6t picture is a *iew o the 9ase inter ace.

8)

Base Handbook

The tables in the database are contained in the tree under the name o the database.

The *iew o the table tree can be closed by clic,ing on the database name. 5or a single database connection this does not ma,e much sense) but it does gi*e a *isible indication o the direct connection.

?nstead o only the database input in .tep 3 o the 7i0ard &see lower status bar() %ibre: ice opens all databases that are a*ailable in 4y.D% to the user IrobbyJ. Dueries must include in the 4y.D% synta6 not only the table name but also the database which contains) or e6ample) the ollowing code'
FROM "myphplib"."A !" A "A !"" "myphplib"."#ate$orie%" A "#ate$orie%"

?t is also possible in e*ery such case to speci y an alias) made up rom the database and table names. 4ore details are gi*en in the chapter on Dueries. Tables can be created and deleted in a database. 5ields with auto *alues may be created when setting up the structure o tables. ?n 4y.D% the starting *alue o such ields de aults to 1.

3hapter 8 3reating a Database

8,

d ase databases
d9ase databases ha*e a ormat where all data is contained in separate) pre*iously initiali0ed tables. %in,s between the tables must be made in program code. 1elations are not supported.

The connection is made to a speci ic older. +ll 295 iles in this older will be included and shown in the :29 database and can be lin,ed together using @ueries. Tables in d9ase ha*e no primary ,ey. They can in principle be described as corresponding to the wor,sheets in Calc.

Base Handbook

Tables can be created and will then be copied as new iles in the older pre*iously selected. The number o di erent ield types or a new d9ase table is clearly less than when the internal /.D%29 ormat is used. ?n the ollowing igure there are still some ield types with the same type name.

The d9ase ormat is especially suitable or the e6change and e6tensi*e editing o data. ?n addition) spreadsheet calculations can directly access d9ase tables. ?t may be better to manipulate the data in 9ase because Calc re@uires the input o the type o character encoding) whereas 9ase simply ta,es the appropriate encoding pro*ided by the operating system. :ld d9ase iles may e6hibit small decoding errors where special characters ha*e been used.

?preadsheets
Calc or F6cel spreadsheets can also be used as the table source or databases. ? ) howe*er) a Calc spreadsheet is used) no editing o the table data will be possible. ? the Calc document is still open) it will be write protected.

The only @uestions to be answered are the location o the spreadsheet ile and whether or not it is password protected. 9ase then opens the spreadsheet and includes all wor,sheets in the document. The irst row is used or the ield names and the wor,sheet names become the table names. 1elationships between spreadsheets cannot be set up in 9ase) as Calc is not suitable or use as a relational database.

3hapter 8 3reating a Database

$hunderbird address book


The +ssistant will automatically see, a connection to an address boo,) or e6ample as used in Thunderbird. The assistant will prompt or the location o the :29 ile that will be produced.

+ll tables are shown. +s in Calc) the tables are not editable. 9ase uses the table data only or @ueries and mail merge applications.

Base Handbook

3hapter *ables

6eneral information on tables


2atabases store data in tables. The main di erence rom the tables in a simple spreadsheet is that the ields into which the data is written must be clearly de ined be orehand. 5or e6ample) a database does not allow a te6t ield to contain numbers or use in calculations. .uch numbers are displayed) but only as strings) whose actual numerical *alue is 0ero. .imilarly) images cannot be included in all types o ields. 2etails o which data types are a*ailable can be obtained rom the Table 2esign window in 9ase. They are shown in the +ppendi6 to this handboo,. .imple databases are based on only one table. +ll data elements are entered independently) which can lead to multiple entry o the same data. + simple address boo, or pri*ate use can be created in this way. /owe*er) the address boo, o a school or a sports association could contain so much repetition o postcodes and locations that these ields are better placed in one or e*en two separate tables. .toring data in separate tables helps'

T T T

1educe repeated input o the same content $re*ent spelling errors due to repeated input ?mpro*e iltering o data in the displayed tables

7hen creating a table) you should always consider whether multiple repetitions) especially o te6t or images &which consume a lot o storage( may occur in the table. ? so) you need to e6port them into another table. /ow to do this in principle is described in Chapter <) !etting .tarted with 9ase) in the %etting &tarted with LibreOffice boo,.

)elationships between tables


This chapter e6plains many o these steps in detail) using an e6ample database or a library' media_without_macros. Constructing the tables or this database is an e6tensi*e Rob) as it co*ers not only the addition o items into a media library but also the subse@uent loan o them.

)elationships for tables in databases


The more relationships there are between tables) the more comple6 is the design tas,. 5igure 2 shows the o*erall table structure o this e6ample database as an o*er*iew) scaled to it the page si0e o this document. To read the content) 0oom the page to 200V.

Base Handbook

'igure 8: 2elationship diagram for the e1ample database media:without:macros

One-to-many relationshi s
The mediaLwithoutLmacros database lists the titles o the media in one table. 9ecause titles can ha*e multiple subtitles or sometimes none at all) the subtitles are stored in a separate table. This relationship is ,nown as oneGtoGmany &1'n(. 4any subtitles may be assigned to one medium) or e6ample the many trac, titles or a music C2. The primary ,ey or the ;edia table is stored as a oreign ,ey in the &ubtitle table. The maRority o relationships between tables in a database are oneGtoGmany relationships.

'igure : <1ample (:n relationship= n:m relationship

3hapter

*ables

"

Many-to-many relationshi s
+ database or a library might contain a table or authorsK names and a table or the media. The connection between an author and) or e6ample) boo,s that author has written) is ob*ious. The library might contain more than one boo, by one author. ?t might also contain boo,s with multiple authors. This relationship is ,nown as manyGtoGmany &n'm(. .uch relationships re@uire a table that acts as an intermediary between the two tables concerned. This is represented in 5igure 3 by the rel:;edia:>uthor table. Thus) in practice) the n'm relationship is sol*ed by treating it as two 1'n relationships. ?n the intermediate table) the ;edia:.D can occur more than once) as can the >uthor:.D. 9ut when using them as a pair) there is no duplication' no two pairs are identical. .o this pair meets the re@uirements or the primary ,ey or the intermediate table.
5or a gi*en *alue or 4ediaL?2) there is only one title o the media and one ?.9". 5or a gi*en *alue or +uthorL?2) there is only one +uthor=s irst and last name. .o) or a gi*en pair o these *alues) there is only one ?.9" and only one +uthor. This ma,es the pair uni@ue.

9ote

One-to-one relationshi s

'igure !: <1ample (:( relationship The library database described abo*e re@uires a table or readers. ?n this table only the ields that are directly necessary were planned in ad*ance. 9ut or a school database) the school class is also re@uired. 5rom the school class records) you can ind borrowersK addresses where necessary. There ore it is not necessary to include these addresses in the database. The school class relationship o pupils is separated rom the reader table) because mapping to classes is not appropriate in all areas. 5rom this arises a 1'1 relationship between the reader and the indi*idual school class assignment. ?n a database or a public library) the addresses o readers are re@uired. 5or each reader there is a single address. ? there are multiple readers at the same address) this structure would re@uire the address to be entered again) since the primary ,ey o the 2eader table is entered directly as the primary ,ey in the >ddress table. $rimary ,ey and oreign ,ey are one and the same in the >ddress table. This is there ore a 1'1 relationship. + 1'1 relationship does not signi y that or e*ery record in a table) there will be a corresponding record in another table. 9ut at most there will be only one corresponding record. + 1'1 relationship

Base Handbook

there ore leads to ields being e6ported which will be illed with content or only some o the records.

$ables and relationships for the e/ample database


The e6ample database &mediaLwithoutLmacros( must satis y three re@uirements' media additions and remo*als) loans) and user administration.

Media addition table


5irst) media must be added into the database so that a library can wor, with them. /owe*er) or a simple summary o a media collection at home) you could create easier databases with the wi0ardP that might be su icient or home use. The central table or 4edia addition is the ;edia table &see 5igure B(.

'igure ": ;edia addition

3hapter

*ables

?n this table all ields that are directly entered are assumed not to be also in use or other media with the same content. 2uplication should there ore be a*oided. 5or this reason) planned ields in the table include the title) the ?.9") an image o the co*er) and the year o publication. The list o ields can be e6tended i re@uired. .o) or instance) librarians might want to include ields or the si0e &number o pages() the series title) and so on. The &ubtitle table contains the detailed content o C2s. +s a C2 can contain se*eral pieces o music) a record o the indi*idual pieces in the main table would re@uire a lot o additional ields &.ubtitle 1) .ubtitle 2) etc.( or the same item would ha*e to be entered many times. The &ubtitle table there ore stands in a n'1 relationship to the ;edia table. The ields o the &ubtitle table are &in addition to the subtitle itsel ( the se@uence number o the subtitle and the duration o the trac,. The Length ield must irst be de ined as a time ield. ?n this way) the total duration o the C2 can be calculated and displayed in a summary i necessary. The authors ha*e a n'm relationship to the media. :ne item can ha*e se*eral authors) and one author might ha*e created se*eral items. This relationship is controlled by the rel:;edia:>uthor table. The primary ,ey o this lin,ing table is the oreign ,ey) ormed rom the >uthor and ;edia tables. The rel:;edia:>uthor table includes an additional sorting &+uthorL.ort( o authors) or e6ample by the se@uence in which they are named in the boo,. ?n addition) a supplementary label such as $roducer) $hotographer and so on is added to the author where necessary. Category) 4ediastyle) Town and $ublisher ha*e a 1'n relationship. 5or the Category= a small library can use something li,e +rt or 9iology. 5or larger libraries) general systems or libraries are a*ailable. These systems pro*ide both abbre*iations and complete descriptions. /ence both ields appear under Category. The -ediastyle is lin,ed to the loan period Loantime. 5or e6ample) *ideo 2V2s might on principle ha*e a loan period o E days) but boo,s might be loaned or 21 days. ? the loan period is lin,ed to any other criteria) there will be corresponding changes in your methodology. The $own table ser*es not only to store location data rom the media but also to store the locations used in the addresses o users. .ince Publishers also recur re@uently) a separate table is pro*ided or them. The ;edia table has in total our oreign ,eys and one primary ,ey) which is used as a oreign ,ey in two tables) as shown in 5igure B.

Loan table
The central table is +oan &see 5igure C(. ?t is the lin, between the 4edia and 1eader tables. ?n case you need to ind out retrospecti*ely who has ta,en out a boo, & or e6ample) i someone notices during the loan process that the boo, is damaged) or i you wish to ma,e a list o the most popular media() the Loan:Date in the loan record is not simply deleted during the return process. ?nstead a 2eturn:Date is recorded. .imilarly) 1eminders are integrated into the loan procedure. Fach reminder is separately entered into the )ecall table so that the total number o reminders can be determined. +s well as an e6tension period in wee,s) there is an e6tra ield in the loan record that enables media to be loaned using a barcode scanner &;edia:.D:B3(. 9arcodes contain) in addition to the indi*idual 4ediaL?2) a chec, digit which the scanner can use to determine i the *alue scanned in is correct. This barcode ield is included here only or test purposes. ?t would be better i the primary ,ey o the 4edia table could be directly entered in barcode orm) or i a macro were used to remo*e the chec, digit rom the entered barcode number be ore storage. 5inally we need to connect the )eader to the loan. ?n the actual reader table) only the name) an optional loc,) and a oreign ,ey lin,ing to the !ender table are included in the plan.

Base Handbook

'igure #: Loan

!ser administration table


5or this table design) two scenarios are en*isaged. The chain o tables shown in 5igure C is designed or school libraries. /ere there is no need or addresses) as the pupils can be contacted through the school. 1eminders do not need to be sent out by post but can be distributed internally. The +ddress chain is necessary in the case o public libraries. /ere you need to enter data that will be needed or the creation o reminder letters. .ee 5igure E.

'igure 9: 2eaders - a &chool class chain and an >ddress chain The 6ender table ensures that the correct &alutation is used in reminders. The writing o reminders can then be automated as ar as possible. ?n addition) some gi*en names can be e@ually masculine or eminine. There ore the separate listing o gender is re@uired e*en when reminders are written out by hand.

3hapter

*ables

The rel@)eader@?choolclass table) li,e the Address table) has a 1'1 relationship with the )eader table. This was chosen because either the school class or the address might be re@uired. :therwise the &choolclass:.D could be put directly into the pupil tableP the same would be true o the complete content o the address table in a public library system. + ?chool class usually consists o a year designation and a stream su i6. ?n a 4Gstream school) this su i6 might run rom a to d. The su i6 is entered in the Class table. The year is in a separate 6rade table. That way) i readers mo*e up a class at the end o each school year) you can simply change the year entry or e*eryone. The Address is also di*ided. ?treet is stored separately because street names within an area are o ten repeated. $ost code and town are separated because there are o ten se*eral post codes or a single area and there ore more post codes than towns. .o compared with the Address table) the Postcode table contains signi icantly ewer records and the $own table e*en ewer. /ow this table structure is put to use is e6plained urther in the Chapter 4) 5orms) in this handboo,.

Creating tables
4ost %ibre: ice users will generally use the graphical user inter ace &!#?( e6clusi*ely to create tables. 2irect entry o .D% commands becomes necessary when) or e6ample) a ield must subse@uently be inserted at a particular position) or a standard *alue must be set a ter the table has been sa*ed. Table terminology' The picture below shows the standard di*ision o tables into columns and rows.

T+9%F
C:%#4"
5ield "ame 5ield Type

C:%#4"
2F5+#%T
5ield "ame 5ield Type

&5?F%2(

&TY$F(

"#%%

&5?F%2(

&TY$F(

"#%%

2F5+#%T

1:7

1ecord

2ata records are stored in a single row o the table. ?ndi*idual columns are largely de ined by the ield) the type) and the rules that determine i the ield can be empty. +ccording to the type) the si0e o the ield in characters can also be determined. ?n addition) a de ault *alue can be speci ied to be used when nothing was entered into the ield. ?n the 9ase !#?) the terms or a column are described somewhat di erently) as shown below.

"otations o the 9aseG!#? C:%#4" 5ield properties


5ield "ame 5ield Type &5?F%2( &TY$F( Fntry re@uired &"#%%/":T "#%%( 2e ault *alue &2F5+#%T(

'ield becomes 'ield ?ame) *0pe becomes 'ield *0pe. 5ield "ame and 5ield Type are entered into the upper area o the Table 2esign window. ?n the lower area you ha*e the opportunity to set) under the 5ield properties the other column properties) in so ar as they can be set using the !#?. %imitations include setting the de ault *alue o a date ield to the actual date o entry. This is possible only by using the appropriate .D% command &see I2irect entry o .D% commandsJ on page 43(.

!7

Base Handbook

9ote

2e ault *alues' The term W2e ault *alueW in the !#? does not mean what the database user generally understands as a de ault *alue. The !#? displays a certain *alue *isibly) which is sa*ed with the data. The de ault *alue in a database is stored in the table de inition. ?t is then written into the ield whene*er this is empty in a new data record. .D% de ault *alues do not appear when editing table properties.

Creation using the graphical user interface


2atabase creation using the graphical user inter ace is described in detail in Chapter <) !etting .tarted with 9ase) in the %etting &tarted with LibreOffice boo,. There ore only the main sources o error are described here. 7hen a table design is sa*ed) you may be as,ed i a primary ,ey should be created. This signi ies that a necessary ield is missing rom the table. 7ithout a primary ,ey) the database cannot access the tables. #sually this ield is gi*en the abbre*iation .D and the data type ?"TF!F1 and allowed to run as an +utoValue. You can ma,e it the primary ,ey with a rightGclic, on the corresponding ield. ? in ormation rom another table is to be pulled through into this one & or e6ample) an address database with separate post codes and locations() you must include in the table a ield o the same data type as the primary ,ey o the other table. ? the Postcode table has as its primary ,ey the ield .D) o data type *in0 .nteger) the Address table must ha*e a ield $ostcode:.D with the data type *in0 .nteger. ?n other words) the Address table will always contain only the number that ser*es as the primary ,ey in the Postcode table. This means that the Address table now has a oreign ,ey in addition to its own primary ,ey. 9asic rules or naming ields in the table' no two ields may ha*e the same name. There ore you cannot ha*e a second ield with the name .D as a oreign ,ey in the +ddress table. There are limits to the changes you can ma,e in the ield type. +n upgrade &longer te6t ield) larger numeric range( is unproblematic as all the *alues already entered will it the new type. + downgrade creates problems and may cause loss o data.

"reatin# an index
.ometimes it is use ul to inde6 other ields or a combination o other ields in addition to the primary ,ey. +n inde6 speeds up searching and can also be used to pre*ent duplicate entries. Fach inde6 has a de ined sort order. ? a table is displayed without sorting) the sort order will be according to the content o the ields speci ied in the inde6.

'igure ): >ccess to .nde1 Design :pen the table or editing by rightGclic,ing and using the conte6t menu. Then you can access inde6 creation with $ools 5 Inde/ #esign.

3hapter

*ables

!(

'igure ,: 3reating a new .nde1 :n the ?nde6es dialog &5igure >() clic, 9ew Inde/ to create an inde6 in addition to the primary ,ey. The new inde6 is automatically gi*en the name inde1(. The Inde/ field speci ies which ield or ields are to be used or this inde6. +t the same time you can choose the .ort order.

'igure (7: *he .nde1 is defined as +ni@ue. ?n principle) an inde6 can also be created rom table ields that do not contain uni@ue *alues. /owe*er in 5igure 10) the ?nde6 detail :ni;ue has been chec,ed) so that the Last?ame ield together with the 'irst?ame ield can only ha*e entries that do not already occur in that combination. .o) or e6ample) 1obert 4Xller and 1obert 4aier are possible) and li,ewise 1obert 4Xller and F*a 4Xller. ? an inde6 is created or one ield only) the uni@ueness applies to that ield. .uch an inde6 is usually the primary ,ey. ?n this ield each *alue may occur only once. +dditionally) in the case o primary ,eys) the ield cannot be "#%% under any circumstances. +n e6ceptional circumstance or a uni@ue inde6 is when there is no entry into a ield &the ield is "#%%(. .ince "#%% can ha*e any arbitrary *alue) an inde6 using two ields is always allowed to ha*e the same entry repeatedly in one o the ields as long as there is no entry in the other.
!8 Base Handbook

9ote

9:++ is used in databases to designate an empty cell) one that contains nothing. "o calculation is possible using a "#%% ield. This contrasts with spreadsheets) in which empty ields automatically contain the *alue 0 &0ero(.

F6ample' ?n a media database) the media number and the loan date are entered when the item is loaned out. 7hen the item is returned) a return date is entered. ?n theory) an inde6 using the ields 4ediaL?2 and 1eturn2ate could easily pre*ent the same item rom being loaned out repeatedly without the return date being noted. #n ortunately this will not wor, because the return date initially has no *alue. The inde6 will pre*ent an item rom being mar,ed as returned twice with the same date but it will do nothing else.

Limitations of #ra hical table desi#n


The se@uence o ields in a table cannot be changed a ter the database has been sa*ed. To display a di erent se@uence re@uires a @uery. :nly the entry o direct .D% commands can insert a ield into a speci ic position in the table. /owe*er) ields already created cannot be mo*ed by this method either. The properties o the tables must be set at the beginning' or e6ample which ields must not be "#%% and which must contain a standard *alue &2e ault(. These properties cannot subse@uently be changed using the !#?. The de ault *alues set here ha*e nothing to do with the de ault *alues within the database itsel . 5or e6ample) you cannot de ine the de ault or a date ield as being the date o entry. That is only possible with directly entered .D% commands.

#irect entry of ?(+ commands


To enter .D% commands directly) go to $ools 5 ?(+.

You can then enter commands into the upper area o the window &shown in 5igure 11(. The lower area shows the result or) i appropriate) the reason why the command ailed. Dueries cannot be created here. 5or these) the Duery 2esign window o ers an e6tra possibility o editing the @uery in .D% 4ode.

3hapter

*ables

'igure ((: Dialog for direct entr0 of &AL commands + summary o the possible commands or the builtGin /.D%29 engine can be ound at http'//www.hs@ldb.org/doc/1.</guide/ch0>.html. The contents are described in the ollowing sections. .ome commands only ma,e sense when dealing with an e6ternal /.D%29 database &.peci y #ser) etc.(. 7here necessary) these are dealt with in the section I7or,ing with e6ternal /.D%29J in the +ppendi6 to this handboo,.
%ibre: ice is based on Version 1.<.0 o /.D%29. The currently a*ailable ser*er *ersion is 2.2. The unctions o the new *ersion are more e6tensi*e. + urther description is gi*en in the installation pac,ages or /.D%29) which can be downloaded rom http'//source orge.net/proRects/hs@ldb/ iles/hs@ldb/.

9ote

$able creation
+ simple command to create a usable table is' &R'A(' (A!)' "(est" *"+," +-( .R+MAR/ #'/" "(ext" 0AR&1AR*23445 CREATE TABLE "Test"' Create a table with the name WTestW. ( )' with the speci ied ield names) ield types and options. "ID" INT PRIMARY KEY, "Text" VARCHAR(50)' 5ield name W?2W with the numeric type integer as the primary ,ey) ield name WTe6tW with the te6t type *ariable te6t length and the te6t si0e limited to B0 characters. &R'A(' 6M'MOR/ 7 &A&1', 7 68)O!A)9 ('M.ORAR/ 7 ('M. 7 (':(9 (A!)' "(able %ame" * ;Field de<i%itio%= 6" ...9 6" ;&o%strai%t ,e<i%itio%=...9 4 6O- &OMM+( >,')'(' 7 .R' 'R0'? RO@ 95

!!

Base Handbook

A-B-4)C D CAC3B# D A6+4 A+E $B-P4)A)C D $B-P D $BF$EG The de ault setting is MEMORY' /.D%29 creates all tables in core memory. This setting also applies to the tables that are written into the embedded database by %ibre: ice 9ase. +nother possibility would be to write the tables to the hard dri*e and use memory only to bu er access to the hard dri*e &CACHED(. Tables in TEXT ormat &such as C.V( are not writable in internal databases that are set up purely in MEMORY) while 9ase cannot access TEMPORARY or TEMP tables. The .D% commands are carried out in this case but the tables are not displayed &and there ore cannot be deleted( using the !#?) and data entered *ia .D% is li,ewise not *isible to the @uery module o the !#?) unless the automatic deletion o the contents a ter the inal commit is pre*ented. +ny re@uest in this case shows a table without any contents. Tables built directly with .D% are not immediately displayed. You must either use 8iew 5 )efresh $ables or simply close the database and then reopen it. HField definition5G "Field %ame" ,ata type 6*-umber o< characters6",ecimal places949 6>,'FAA)( ",e<ault value" 7 8'-'RA(', !/ ,'FAA)( A +,'-(+(/ * (AR( @+(1 ;%=6" +-&R'M'-( !/ ;m=94?9 7 66-O(9 -A))9 6+,'-(+(/9 6.R+MAR/ #'/9 +llows de ault *alues to be included in the ield de inition. 5or te6t ields) you can enter te6t in single @uotes or NULL. The only .D% unction allowed is CURRENT_U ER. This only ma,es sense i /.D%29 is being used as an e6ternal .er*er database with se*eral users. 5or date and time ields) a date) a time) or a combination o the two can be entered in single @uotes or else "#%%. You must ensure that the date ollows the +merican con*entions &yyyyG mmGdd() that time has the ormat hh'mm'ss) and that a combined date/time *alue has the ormat yyyyGmmGdd hh'mm'ss. +llowed .D% unctions' or the current date or the current time or the current data time stamp CURRENT_DATE, TODAY, CURDATE() CURRENT_TIME, NO!, CURTIME() CURRENT_TIME TAMP, NO!.

5or boolean 5ields &yes/no( the e6pressions "AL E, TRUE, NULL can be entered. These must be entered without single @uotes. 5or numeric ields) any *alid number in the range) or "#%% is possible. /ere too) i you enter NULL) do not use @uotes. 7hen entering decimals) ma,e sure that the decimal point is a dot &period( and not a comma. 5or binary ields &images) etc.( any *alid he6adecimal string in single @uotes or NULL is possible. + he6adecimal e6ample string is' =0004 =) which represents 3 bytes) irst 0) then 4 and inally 2BB &06 (. +s binary ields in practice need only be entered or images) you need to ,now the binary code o the image that is to ser*e as a de ault. NOT NULL# The ield *alue cannot be -A)). This condition can only be gi*en in the ield de inition.
/e6adecimal system' "umbers are based on 1C. + mi6ed system consisting o the numbers 0 to > and the letters a to pro*ides 1C possible digits or each column. 7ith two columns) you can ha*e 1CH1CY2BC possible *alues. This corresponds to 1 9yte &2<(.

9ote

3hapter

*ables

!"

HConstraint definition5G 6&O- (RA+-( "-ame"9 A-+BA' * "Field_%ame C" 6""Field_%ame D"...9 4 7 .R+MAR/ #'/ * "Field_%ame C" 6""Field_%ame D"...9 4 7 FOR'+8- #'/ * "Field_%ame C" 6""Field_%ame D"...9 4 R'F'R'-&' "other_table_%ame" * "Field_%ame_C" 6""Field_%ame D"...94 6O- >,')'(' 7 A.,A('? >&A &A,' 7 '( ,'FAA)( 7 '( -A))?9 7 &1'&#*; earch_co%ditio%=4 Constraints de ine conditions that must be ul illed when data is entered. Constraints can be gi*en a name. UNI$UE (""%e&'_()*e")# the ield *alue must be uni@ue within that ield PRIMARY KEY (""%e&'_()*e")# the ield *alue must be uni@ue and cannot be NULL &primary ,ey( "OREI+N KEY (""%e&'_()*e") RE"ERENCE ,"-t.e/_t)0&e_()*e"1 (""%e&'_()*e")# The speci ied ields o this table are lin,ed to the ields o another table. The ield *alue must be tested or re erential integrity as oreign ,eysP that is) there must be a corresponding primary ,ey in the other table) i a *alue is entered here. 2ON 3DELETE 4 UPDATE5 3CA CADE 4 ET DE"AULT 4 ET NULL56# ?n the case o a oreign ,ey) this speci ies what is to happen i ) or e6ample) the oreign record is deleted. ?t ma,es no sense) in a loan table or a library) to ha*e a user number or which the user no longer e6ists. The corresponding record must be modi ied so that the relationship between the tables remains *alid. #sually the record is simply deleted. This happens i you select ON DELETE CA CADE. CHECK(, e)/7._7-('%t%-(1)# 5ormulated as a !HERE condition) but only or the current record. You need constraints when the relationship between tables or the inde6 or certain ields must be de ined. A49 C4--I$ I#B+B$B D P)B?B)8BJ )40?EG The content o tables o the type TEMPORARY or TEMP is erased by de ault when you ha*e inished wor,ing with a particular record &ON COMMIT DELETE RO! (. This allows you to create temporary records) which contain in ormation or other actions to be carried out at the same time. ? you want a table o this type to contain data a*ailable or a whole session & rom opening a database to closing it() choose ON COMMIT PRE ERVE RO! .

$able modification
.ometimes you might wish to insert an additional ield into a particular position in the table. .uppose you ha*e a table called Addresses with ields .D) ?ame) &treet) and so on. You reali0e that perhaps it would be sensible to distinguish irst names and last names. A)('R (A!)' "Addresses" A,, "First -ame" 0AR&1AR*D24 !'FOR' "-ame"5 ALTER TABLE "A''/esses"' +lter the table with the name W+ddressesW. ADD ""%/st N)*e" VARCHAR(85)' insert the ield W5irst"ameW with a length o 2B characters. BE"ORE "N)*e"' be ore the ield W"ameW. The possibility o speci ying the position o additional ields a ter the creation o the table is not a*ailable in the !#?. A)('R (A!)' "(able_%ame" A,, 6&O)AM-9 ;Field_de<i%itio%= 6!'FOR' "already_existi%$_<ield_%ame"95 The additional designation COLUMN is not necessary in cases where no alternati*e choices are a*ailable.
!# Base Handbook

A)('R (A!)' "(able_%ame" ,RO. 6&O)AM-9 "Field_%ame"5 The ield W5ield nameW is erased rom the table *able:name. /owe*er this does not ta,e place i the ield is in*ol*ed in a *iew or as a oreign ,ey in another table. A)('R (A!)' "(able_%ame" A)('R &O)AM- "Field_%ame" R'-AM' (O "-ew_<ield_%ame" Changes the name o a ield. A)('R (A!)' "(able_%ame" A)('R &O)AM- "Field_%ame" '( ,'FAA)( ; ta%dard value=?5 .ets a speci ic de ault *alue or the ield. NULL remo*es an e6isting de ault *alue. A)('R (A!)' "(able_%ame" A)('R &O)AM- "Field_%ame" .ets or remo*es a NOT NULL condition or a ield. '( 6-O(9 -A))

A)('R (A!)' "(able_%ame" A)('R &O)AM- ;Field de<i%itio%=5 The ield de inition corresponds to the one rom the Table creation with the ollowing restrictions'

T T T T

The ield must already be a primary ,ey ield to accept the property IDENTITY. IDENTITY means) that the ield has the property +utoValue. This is possible only or INTE+ER or BI+INT ields. 5or these ield type descriptions) see the +ppendi6 to this handboo,. ? the ield already has the property IDENTITY but it is not repeated in the ield de inition) the e6isting IDENTITY property is remo*ed. The de ault *alue will become that speci ied in the new ield de inition. ? the de inition o the de ault *alue is le t blan,) any de ault already de ined is remo*ed. The property NOT NULL continues into the new de inition) i not otherwise de ined. This is in contrast to the de ault *alue. ?n some cases) depending on the type o modi ication) the table must be empty in order or the change to occur. ?n all cases the change will ha*e e ect only i it is possible in principle & or e6ample a change rom NOT NULL to NULL( and the e6isting *alues can all be translated & or e6ample a change rom TINYINT to INTE+ER(.

A)('R (A!)' "(able_%ame" A)('R &O)AM- "Field_%ame" R' (AR( @+(1 ;-ew_<ield_value= This command is used e6clusi*ely or an IDENTITY ield. ?t determines the ne6t *alue or a ield with the +uto*alue unction set. ?t can be used) or e6ample) when a database is initially used with test data) and subse@uently pro*ided with real data. This re@uires the contents o the tables to be deleted and a new *alue such as W1W to be set or the ield. A)('R (A!)' "(able_%ame" A,, 6&O- (RA+-( "&o%ditio%_%ame"9 &1'&# *; earch_co%ditio%=45 This adds a search condition introduced by the word CHECK. .uch a condition will not apply retrospecti*ely to e6isting records) but it will apply to all subse@uent changes and newly entered records. ? a constraint name is not de ined) one will be assigned automatically. F6ample' A)('R (A!)' ")oa%" A,, &1'&# *+F-A))*"Retur%_,ate""")oa%_,ate"4=E")oa%_,ate"4 The L-)( table needs to be protected rom input errors. 5or e6ample) you must pre*ent a return date being gi*en that is earlier than the loan date. "ow i this error occurs during the return process) you will get an error message C.e79 7-(st/)%(t :%-&)t%-( ; A)('R (A!)' "(able_%ame" A,, 6&O- (RA+-( "&o%strai%t_%ame"9 A-+BA' *"Field_%ameC"" "Field_%ameD" ...45
3hapter *ables !9

/ere a condition is added that orces the named ields to ha*e di erent *alues in each record. ? se*eral ields are named) this condition applies to the combination rather than the indi*idual ields. NULL does not count here. + ield can there ore ha*e the same *alue repeatedly without causing any problems) i the other ield in each o the records is NULL. This command will not wor, i there is already a UNI$UE condition or the same ield combination. A)('R (A!)' "(able_%ame" A,, 6&O- (RA+-( "&o%strai%t_%ame"9 .R+MAR/ #'/ *"Field_%ameC"" "Field_%ameD" ...45 +dds a primary ,ey) optionally with a constraint) to a table. The synta6 o the constraint is the same as when a table is created. A)('R (A!)' "(able_%ame" A,, 6&O- (RA+-( "&o%strai%t_%ame"9 FOR'+8- #'/ *"Field_%ameC"" "Field_%ameD" ...4 R'F'R'-&' "(able_%ame_o<_a%other_table" *"Field_%ameC_other_table"" "Field_%ameD_other_table" ...4 6O- >,')'(' 7 A.,A('? >&A &A,' 7 '( ,'FAA)( 7 '( -A))?95 This adds a oreign ,ey &"OREI+N KEY( to the table. The synta6 is the same as when a table is created. The operation will terminate with an error message) i any *alue in the table does not ha*e a corresponding *alue in the table containing that primary ,ey. F6ample' The 9ame and Address tables are to be lin,ed. The 9ame table contains a ield with the name >ddress:.D. The *alue o this should be lin,ed to the ield .D in the Address table. ? the *alue W1W is ound in >ddress:.D but not in the .D ield o the Address table) the lin, will not wor,. ?t will not wor, either i the two ields are o di erent types. A)('R (A!)' "(able_%ame" ,RO. &O- (RA+-( "&o%strai%t_%ame"5 This command remo*es the named constraint &UNI$UE) CHECK) "OREI+N KEY( rom a table. A)('R (A!)' "(able_%ame" R'-AM' (O "%ew_table_%ame"5 5inally this command changes only the name o a table.

%eletin# tables
,RO. (A!)' "(able %ame" 6+F ':+ ( 9 6R' (R+&( 7 &A &A,'95 2eletes the table WTable nameW. I" EXI T pre*ents an error occurring i this table does not e6ist. RE TRICT is the de ault arrangement and need not be e6plicitly chosenP it means that deletion does not occur i the table is lin,ed to another table by the use o a oreign ,ey or there is an acti*e *iew o this table. Dueries are not a ected as they are not stored within /.D%29. ? instead you choose CA CADE) all lin,s to the table WTableLnameW are deleted. ?n the lin,ed tables) all oreign ,eys are set to "#%%. +ll *iews re erring to the named table are also completely deleted.

+inking tables
?n principle you can ha*e a database without lin,s between tables. The user must then ensure during data entry) that the relationships between the tables remain correct. This usually occurs through the use o suitable input orms that manage this.

!)

Base Handbook

2eleting records in lin,ed tables is not a simple matter. .uppose you wish to delete a particular street rom the &treet table in 5igure E) where this ield is lin,ed with the >ddress table as a oreign ,ey in that table. The re erences in the >ddress table would disappear. The database does not allow this) once the relationship has been created. ?n order to delete the &treet) the precondition must be ul illed) that it is no longer re erenced in the >ddress table. 9asic lin,s are made using $ools 5 )elationships. This creates a connection line rom the primary ,ey in one table to the de ined oreign ,ey in the other. You may recei*e the ollowing error message when creating such a lin,'

This message shows some te6t in Fnglish and the internal .D% command that caused the error. Column types do not match in statementS+s the .D% command is displayed as well) the re erence is clearly to the columns >ddress.str:.D and &treet..D. 5or test purposes one o these ields was de ined as an ?nteger) the other as Tiny ?nteger. There ore no lin, could be created since the one ield cannot ha*e the same *alue as the other.

?n this case the column types match. The .D% statement is the same as in the irst e6ample. 9ut again there is an error' Integrity constraint violation > no parent 1= tableG Address ... SThe integrity o the relationship is not ensured. ?n the ield o the +ddress table) >ddress.str:.D) there is a number 1) which is not present in &treet..D. The parent table here is &treet) since its primary ,ey is the one that must e6ist. This error is *ery common) when two tables are to be lin,ed and some ields in the table with the prospecti*e oreign ,ey already contain data. ? the oreign ,ey ield contains an entry that is not present in the parent table &the table containing the primary ,ey() this is an in*alid entry.

3hapter

*ables

!,

? the lin,ing is carried out success ully and subse@uently there is an attempt to enter a similarly in*alid record into the table) you get the ollowing error message'

+gain this is an integrity *iolation. 9ase re uses to accept the *alue 1 or the ield str:.D a ter the lin, has been made because the &treet table contains no such value in the ?2 ield.

'igure (8: Links can be edited with a right-click The properties o a lin, can be edited so that the deletion o a record rom the &treet table will simultaneously set to "#%% the corresponding entries in the >ddress table. The properties shown in 5igure 12 always relate to an action lin,ed to the change in a record rom the table containing the corresponding primary ,ey. ?n our case this is the &treet table. ? the primary key of a record in this table is altered K:pdateL) the ollowing actions might ta,e place. 9o action Changing the primary ,ey &treet..D is not allowed in this case) as it would brea, the relationship between the tables. :pdate cascade ? the primary ,ey &treet..D is changed) the oreign ,ey is automatically changed to its new *alue. This ensures that the lin,age is not damaged. 5or e6ample) i a *alue is changed rom 3 to 4) all records rom the >ddress table that contain the oreign ,ey >ddress.&treet:.D with the *alue 3) ha*e it changed to 4.

"7

Base Handbook

'igure ( : <diting the properties of a relationship ?et null +ll records which contain this particular primary ,ey will now ha*e no entry in the oreign ,ey ield >ddress.&treet:.D= the ield will be "#%%. ?et default ? the primary ,ey &treet:.D is changed) the *alue o >ddress.&treet:.D originally lin,ed to it is set to the pre*iously de ined de ault *alue. 5or this purpose we need an unambiguous de inition o a de ault *alue. The %ibre: ice 9ase !#? up to Version 3.B does not seem to pro*ide this. ? the de ault is set using the .D% statement' A)('R (A!)' "Address" A)('R &O)AM- " treet_+," '( ,'FAA)( C5 the lin, de inition ensures that the ield will return to this *alue in the case o an #pdate. .o i the primary ,ey in the &treet table is changed) the corresponding oreign ,ey in the >ddress table will be set to 1. This is use ul when a record is re@uired to ha*e a street ield) in other words this ield cannot be "#%%. 9ut be care ulU ? 1 is not in use) you will ha*e created a lin, to a nonGe6istent *alue. ?n this case /.D%29 seems to ha*e been designed without due thought. ?t is there ore possible to destroy the integrity o the relationship.

Attention

? the de ault *alue in a oreign ,ey ield is not lin,ed to a primary ,ey o the oreign table) a lin, to a *alue would be created) that isn=t possible. The re erential integrity o the database would be destroyed.

?t would be better not to use the possibility to set the *alue to de ault. ? a record is deleted rom the &treet table) the ollowing options are a*ailable. 9o Action "o action ta,es place. ? the re@uested deletion a ects a record in the +ddress table) the re@uest will be re used.

3hapter

*ables

"(

Cascading #elete ? a record is deleted rom the &treet table and this a ects a record in the >ddress table) that record will also be deleted. That might seem strange in this conte6t but there are other table structures in which it ma,es a lot o sense. .uppose you ha*e a table o C2s and a table which stores the titles on these C2s. "ow i a record in the C2 table is deleted) many titles in the other table ha*e no meaning as they are no longer a*ailable to you. ?n such cases) a cascading deletion ma,es sense. ?t means that the user does not need to delete all these titles be ore deleting the C2 rom the database. ?et to 9ull This is the same as or the update option. ?et to #efault This is the same as or the update option and re@uires the same precautions.
To a*oid error messages rom the database as ar as possible) since these may not always be comprehensible to the user) the ?o >ction option should de initely be a*oided.

$ip

Bntering data into tables


2atabases that consist o only a single table usually do not re@uire an input orm unless they contain a ield or images. /owe*er as soon as a table contains oreign ,eys rom other tables) users must either remember which ,ey numbers to enter or they must be able to loo, at the other tables simultaneously. ?n such cases) a orm is use ul.

Bntry using the ase 6:I


Tables in the table container are opened by doubleGclic,ing them. ? the primary ,ey is an automatically incrementing ield) one o the *isible ields will contain the te6t >utoBalue. "o entry is possible into the >utoBalue ield. ?ts assigned *alue can be altered i re@uired) but only a ter the record has been committed.

'igure (!: <ntr0 into tables C Hiding columns 'igure (": <ntr0 into tables C +nhiding columns ?ndi*idual columns in the Table 2ata View can be hidden. 5or e6ample) i the primary ,ey ield does not need to be *isible) this can be speci ied in the table in data entry *iew by rightGclic,ing on the column header. This setting is stored with the !#?. The column continues to e6ist in the table and can always be made *isible again. Fntry into the table usually ta,es place rom le t to right using the ,eyboard with the *ab or <nter ,eys. You can also use the mouse.

"8

Base Handbook

7hen you reach the last ield o a record) the cursor automatically Rumps to the ne6t record. The pre*ious entry is committed to storage. +dditional storage using File 5 ?ave is not necessary and indeed not possible. The data is already in the database.

Caution

5or the /.D%29) data is in wor,ing memory. ?t will only be trans erred to the hard dri*e when 9ase is closed &un ortunately rom the *iewpoint o data security(. ? 9ase or some reason does not close down in an orderly ashion) this can lead to loss o data.

? no data is entered into a ield that has been pre*iously de ined during table design as mandatory &NOT NULL() the appropriate error message is displayed' Atte*<t t- %(se/t (=&& %(t- ) (-(>(=&&)0&e 7-&=*( ; The corresponding column) the table and the .D% command &as translated by the !#?( are also displayed. Changing a record is easy' ind the ield) enter a di erent *alue) and lea*e the row again.

To delete a record) select the row by clic,ing its header &the grey area to the le t() rightGclic, and choose #elete )ows. The .ort) .earch) and 5ilter unctions are *ery use ul or retrie*ing particular records.

&ortin# tables

'igure (#: Auick &ort The @uic, sort option hides behind the AMN and NMA buttons. :ne ield is selected) one clic, on the button) and the data is sorted by that column. The igure shows a descending sort by the *itle ield. Duic, sort sorts only by one column. To sort by se*eral columns simultaneously) a urther sort unction is pro*ided.

3hapter

*ables

"

The ield name o the column and the current sort order are selected. ? a pre*ious @uic, sort has been carried out) the irst row will already contain the corresponding ield name and sort order.

'igure (9: &orting b0 more than one column

&earchin# tables

5unctions or searching records are e6tensi*e and perhaps not the irst choice or locating a particular record or users accustomed to search engines.
9e ore you search) ma,e sure the columns you will be searching are wide enough to show correctly the records that you will ind. The search window remains in the oreground and you will not be able to correct the settings or column width in the underlying table. To reach the table) you must brea, o the search.

$ip

The search ta,es o*er terms rom the ield rom which it was in*o,ed. To ma,e the search e ecti*e) the search area should be limited as ar as possible. ?t would be pointless to search or the abo*e te6t rom the *itle ield in the >uthor ield. ?nstead) the ield name *itle is already suggested as the single 5ield name. 5urther settings or the search can ma,e things easier through speci ic combinations. You can use the normal .D% placeholders &"_" or a *ariable character) "?" or an arbitrary number o *ariable characters) "@" as an escape character) to enable these special characters themsel*es to be searched or(. 1egular e6pressions are described in detail in %ibre: ice /elp. +part rom that) the /elp a*ailable or this module is rather sparse.

"!

Base Handbook

'igure (): <ntr0 mask for a 2ecord search

'igure (,: Limiting the similarit0 search The similarity search unction is use ul when you need to e6clude spelling mista,es. The higher the *alues that you set) the more records will be shown in the inal list. This search module is most suitable or people who ,now) rom regular use) e6actly how to achie*e a gi*en result. 4ost users are more li,ely to succeed in inding records by using a ilter. Chapter 4 o this handboo, describes the use o orms or searching) and how the use o .D% and macros can accomplish a ,eyword search.

3hapter

*ables

""

'ilterin# tables

You can ilter a table @uic,ly by using the AutoFilter. $lace the cursor in a ield) and one clic, on the icon causes the ilter to ta,e o*er the content o this ield. :nly those records are shown or which the chosen ield has the same content. The igure below shows iltering according to an entry in the Pub@Cear column.

The ilter is acti*e) as shown by the ilter icon with a green chec, mar,. The ilter symbol is shown pressed in. ? the button is clic,ed again) the ilter continues to e6ist) but all records are now shown. .o) i you want) you can always return to the iltered state. Clic,ing on the )emove FilterO?ort icon at the e6treme right causes all e6isting ilters and sorts to be remo*ed. The ilters become inacti*e and can no longer be reco*ered with their old *alues.
You can still enter records normally into a iltered table or one that has been restricted by a search. They remain *isible in the table *iew until the table is updated by pressing the )efresh button.

$ip

The ?tandard Filter icon opens a dialog inwhich you can ilter using se*eral simultaneous criteria) similar to doing a sort. ? +uto5ilter is in use) the irst line o the .tandard 5ilter will already show this e6isting ilter criterion.

'igure 87: ;ultiple Data 'iltering using the &tandard 'ilter

"#

Base Handbook

The .tandard 5ilter pro*ides many o the unctions o .D% data iltering. The ollowing .D% commands are a*ailable. (!) "ondition
Y Z[ Z ZY [ [Y li,e not li,e empty "ot empty

%escri tion
F6act e@ualityP corresponds to like) but without any additional placeholders #ne@ual %ess than %ess than or e@ual !reater than !reater than or e@ual 5or te6t) written in @uotation mar,s & A A(P "_" or a *ariable character) "?" or an arbitrary number o *ariable characters :pposite o &%9e) in .D% NOT LIKE "o entry) not e*en a space character. ?n .D% this is e6pressed by the term NULL :pposite o empty) in .D% NOT NULL

9e ore one ilter criterion can be combined with another) the ollowing row must ha*e at least one ield name selected. ?n 5igure 20) the word A none A is shown instead o a ield name) so the combination is not acti*e. The combination operators a*ailable are AND and OR. The ield name can be a new ield name or a pre*iously selected one. F*en or large data collections) the number o retrie*ed records can be reduced to a manageable set with s,ill ul iltering using these three possible conditions. ?n the case o iltering orms too) there are some urther possibilities &described in the ollowing chapter( which are not pro*ided by the !#?.

#irect entry using ?(+


2irect data entry using .D% is use ul or entering) changing or remo*ing multiple records with one command.

Enterin# new records


+- 'R( +-(O "(able_%ame" 6* "Field_%ame" 6"...9 49 > 0A)A' *"Field value" 6"...94 7 ; electFFormula=?5 ? no W5ieldLnameW is speci ied) all ields must be completed and in the right order &as laid down in the table(. That includes the automatically incremented primary ,ey ield) where present. The *alues entered can also be the result o a @uery &Z.electG5ormula[(. 4ore e6act in ormation is gi*en below. +- 'R( +-(O "(able_%ame" *"Field_%ame"4 0A)A' *G(estG45 &A)) +,'-(+(/*45 ?n the table) in the column W5ieldLnameW) the *alue =Test= is inserted. The automatically incremented primary ,ey ield W?2W is not touched. The corresponding *alue or the W?2W needs to be created separately by using C+%% ?2F"T?TY&(. This is important when you are using macros) so that the *alue o this ,ey ield can be used later on. +- 'R( +-(O "(able_%ame" *"Field_%ame"4 "-ame_o<_other_table"5
3hapter *ables

')'&( "Other_<ield%ame" FROM

"9

?n the irst table) as many new records are inserted into W5ieldLnameW) as are present in the column W:therL ieldnameW in the second table. "aturally a .electG5ormula can be used here to limit the number o entries.

Editin# existin# records


A.,A(' "(able_%ame" '( "Field_%ame" E ;'xpressio%= 6" ...9 6@1'R' ;'xpressio%=95 7hen you are modi ying many records at once) it is *ery important to chec, care ully the .D% command you are entering. .uppose that all students in a class are to be mo*ed up one year' A.,A(' "(able_%ame" '( "/ear" E "/ear"HC "othing could be aster' +ll data records are altered with a single command. 9ut o course you must now determine which students should not ha*e been a ected by this change. ?t would ha*e been simpler to chec, a Yes/"o ield or the repetition o a year and then to mo*e up only those students or which this ield was not chec,ed' A.,A(' "(able_%ame" '( "/ear" E "/ear"HC @1'R' "Repetitio%" E FA) ' These conditions only unction when the ield in @uestion can only ta,e the *alues "AL E and TRUEP it may not be NULL. ?t would be sa er i the condition were ormulated as !HERE "Re<et%t%-(" ,1 TRUE. :ther calculation steps are also possible with #pdate. ? ) or e6ample) wares costing more than \1B0.00 are to be included in a special o er and the price reduced by 10V) this can be carried out as ollows' A.,A(' "(able_%ame" '( ".rice" E ".rice"I3"J @1'R' ".rice" =E C23

%eletin# existin# records


,')'(' FROM "(able_%ame" 6@1'R' ;'xpressio%=95 7ithout the conditional e6pression the command ,')'(' FROM "(able_%ame" deletes the entire content o the table. 5or this reason it is pre erable or the command to be more speci ic. 5or e6ample) i the *alue o the primary ,ey is gi*en) only this precise record will be deleted. ,')'(' FROM "(able_%ame" @1'R' "+," E 25 ? ) in the case o a loan) the media record is to be deleted when the item is returned) this can be done using ,')'(' FROM "(able_%ame" @1'R' -O( "Retur%_date" + or alternati*ely with ,')'(' FROM "(able_%ame" @1'R' "Retur%_date" + -A))5

-O( -A))5

")

Base Handbook

Problems with these data entry methods


Fntry using a table alone ta,es no account o lin,s to other tables. This is clear rom an e6ample o a media loan.

The +oan table consists o oreign ,eys or the item being lent &;edia:.D( and the corresponding reader &2eader:.D( as well as a loan date &Loan:Date(. ?n the table) there ore) we need to enter at the time o the loan two numeric *alues &4edia number and 1eader number( and a date. The primary ,ey is automatically entered in the .D ield. 7hether the reader actually corresponds to the number is not apparent unless a second table or the readers is open at the same time. 7hether the item was loaned out with the correct number is also not apparent. /ere the loan must rely on the label on the item or on another open table. +ll this is much easier to accomplish using orms. /ere the users and the media can be loo,ed up using list bo6 controls. ?n orms) the names o user and item are *isible and their numeric identi iers are hidden. ?n addition) a orm can be so designed that a user can be selected irst) then a loan date) and each set o media are assigned this one date by number. Flsewhere these numbers can be made *isible with the e6actly corresponding media descriptions. 2irect entry into tables is use ul only or databases with simple tables. +s soon as you ha*e relationships between tables) a specially designed orm is better. ?n orms) these relationships can be better handled by using subG orms or list ields.

3hapter

*ables

",

3hapter ! 'orms

Forms make data entry easier


5orms are used when direct entry into a table is incon*enient) to pic, up errors in data entry promptly) or when too many tables ma,e direct management o data impossible.

Desktop
+ 'orm in 9ase is a structure invisible to the user. ?t ser*es within 9ase to allow contact with the database.

5orm
Control ield 1 Control ield 2 Control ield 3 Control ield ...

9ote

7hat is visible to the user is the set o 3ontrols) which ser*e or the entry or display o te6t) numbers) and so on. These controls are di*ided by the !#? into *arious types.

Creating forms
The simplest way to create a orm is to use the 5orm 7i0ard. #se o the 7i0ard to create a orm is described in Chapter <) !etting .tarted with 9ase) in the %etting &tarted with LibreOffice guide. That chapter also e6plains how you can urther modi y the orm a ter using the 7i0ard. This handboo, describes the creation o a orm without using the 7i0ard. ?t also describes the properties o the *arious types o controls in a orm.

A simple form
7e start by using the tas, 3reate 'orm in Design Biew in the 5orms area o the main 9ase window.

This calls up the 5orm Fditor and the 5orm .hown in 2esign View window appears &5igure 21(. The 5orm Controls toolbar is doc,ed on the le t side. The 5orm 2esign toolbar &5igure 22( is doc,ed at the bottom. ? these toolbars do not appear automatically) use 8iew 5 $oolbars to display them. 7ithout these toolbars) it is not possible to create a orm. The blan, area shows a grid o dots. This grid helps you to position the controls accurately) especially in relation to each other. The symbols at the right end o the 5orm 2esign toolbar show that the grid is *isible and acti*e.

#8

Base Handbook

'igure 8(: 'orm shown in Design Biew

$oolbars for form design


"ow we will create a orm on the empty page. This can be done in two ways'

T T

?n*o,e the 5orm "a*igator to set up a orm) or 2esign the orm controls and set up the orm by using the conte6t menu.

&ettin# u a form with the 'orm *avi#ator


To display the 5orm "a*igator) clic, the 5orm "a*igator button &shown in 5igure 22(. + window appears &5igure 23(P it shows only one older) labeled Forms. This is the highest le*el o the area that we are editing. .e*eral orms can be accommodated here.

3hapter ! 'orms

'igure 88: >vailable buttons on the 'orm Design toolbar

'igure 8 : +sing the 'orm ?avigator to create a new form ?n the 5orm "a*igator &5igure 23() rightGclic, on Forms to open a conte6t menu. Choose 9ew 5 Form to create a new orm. The other choices in the conte6t menu &4pen in #esign -ode and Automatic Control Focus( correspond to buttons in 5igure 22P we will discuss them later. The orm carries the de ault name Form. You can change this name immediately or later. ?t has no signi icance unless you need to access some part o the orm using macros. The only thing you need to ensure is that two elements with the same name do not occur on the same le*el in the older tree.

#!

Base Handbook

The conte6t menu o the orm &shown below( pro*ides the way to create orm properties.

"reatin# a form usin# a form field


The 5orm Controls toolbar &5igure 24( ma,es a*ailable some ields or your orm. The irst our elements are identical to those o the 5orm 2esign toolbarP they are ollowed by commonly used orm control types &a control consists o a ield plus a label(.

'igure 8!: >vailable buttons on the 'orm 3ontrols toolbar

'igure 8": >vailable buttons on the ;ore 3ontrols toolbar

3hapter ! 'orms

#"

7hen you select a orm control) you automatically create a orm. 5or e6ample) suppose you choose a te6t ield' the cursor changes shape and a rectangular shape may be drawn on the white sur ace o the orm. Then) on the stippled sur ace o the orm) a te6t ield appears.

"ow you can create the orm by rightGclic,ing and using the conte/t menu or the control &5igure 2C(. .elect the Form menu option &highlighted in the illustration( to set properties or the orm you ha*e Rust created. The orm has the de ault name 5orm. 'igure 8#: 3onte1t menu for form

Form properties
7hen the orm properties are called up using the conte6t menu in the 5orm "a*igator or the conte6t menu o a orm control) a 5orm $roperties window appears. ?t has three tabs' 6eneral) #ata and Bvents. 6eneral tab /ere you can change the "ame o the orm. ?n addition there are design possibilities that ha*e no signi icance inside 9ase. They show only the more general possibilities or design using a orm editorP when you create a 7eb orm you will need to use them.

+2L' 2estination or the data. 'rame' .ection o the destination website to be addressed where necessary. &ubmission encoding' in addition to the normal character encoding or transmission to the #1%) you can speci y here te6t encoding and multipart coding & or e6ample) or trans er o data(. *0pe of submission' !FT &*isible *ia the #1% attached to the ilenameP you can see this o ten in the web i you use a search engine( or $:.T &not *isibleP suitable or large data *olumes(.

##

Base Handbook

#ata tab

5or creating internal orms in 9ase) this is the most important tab. /ere you can set the ollowing initial properties or the orm' 3ontent t0pe' Choose between *able) Auer0 and &AL command. 7hile Table can always be used or data entry into a orm) this is not always the case or Duery & or more in ormation) see Chapter B) Dueries) in this boo,( or direct entry o a .D% command. /ere we are dealing with a @uery that is not *isible in 9ase=s @uery container but has in principle the same structure. 3ontent' +ccording to whether Table or Duery was chosen abo*e) all available tables and @ueries are listed. ? a .D% command is to be created) you can in*o,e the Duery Fditor by using the button with the three dots to the right o the Content ield. >nal0/e &AL command' ? the analysis o .D% commands should not be permitted &because) or e6ample) you are using code that the !#? cannot show correctly() you should choose 9o here. /owe*er this will pre*ent the orm accessing the underlying data using a ilter or a sort. 'ilter' /ere you can set a ilter. To get help with this) clic, the button to the right o the ield. .ee also Chapter 3) Tables) in this boo,. &ort' /ere you can set up a .ort or your data. To get help) clic, the button to the right o the ield. .ee also Chapter 3) Tables. >llow additions' .hould the entry o new data be allowed; 9y de ault this is set to Ces. >llow modifications' .hould editing o the data be allowed; 9y de ault also Ces. >llow deletions' The deletion o data is also allowed by de ault. >dd data onl0' ? you choose this option) an empty orm will always be displayed. There will be no access to e6isting data) which can neither be edited nor *iewed. ?avigation bar' The appearance o the "a*igation 9ar at the bottom o the screen can be switched on or o . There is also a possibility) when you ha*e a sub orm) always to show the "a*igation 9ar or the main orm) so that acti*ation o this toolbar a ects the main orm only. This setting or the "a*igation 9ar is not rele*ant to the internal na*igation toolbar that can be added as a orm control i re@uired. 30cle' The Default option or 9ase databases is that a ter entry into the last ield in a orm) the Tab ,ey ta,es you to the irst ield o the ne6t record A that is) a new record will be created. 5or
3hapter ! 'orms #9

databases) this has the same e ect as >ll records. 9y contrast) i you choose >ctive record) the cursor will mo*e only within the recordP when it reaches the last ield) it will Rump bac, to the irst ield in that record. 3urrent page re ers particularly to /T4% 5orms. The cursor Rumps rom the end o a orm to the ne6t orm on that page urther down. Bvents tab

Bvents can trigger macros. + clic, on the button on the right &]( allows macros to be lin,ed to the e*ent. 2eset' The orm is emptied o all new entries that ha*e not yet been sa*ed. Before submitting' 9e ore the orm data are sent. This is only meaning ul or 7eb orms. Dhen loading' :nly when opening the orm. "ot when loading a new record into the orm. 2eloading' This ta,es place when the content o the orm is re reshed) or e6ample by using a button on the "a*igation 9ar. +nloading' This option seems not to unction. ?t would be e6pected to re er to the closing o the orm. 2ecord action' This includes) or e6ample) storage using a button. ?n tests) this action regularly duplicates itsel P macros run twice in succession. 2ecord change' The opening o a orm counts as a record change. 7hene*er one record changes to another within the orm) this action li,ewise occurs twice. 4acros are there ore run twice in succession. 'ill parameters: This macro will be run i a parameter @uery is to be in*o,ed in a sub orm) but or some reason the parameter is not correctly transmitted rom the main orm. ? this e*ent is not caught) a parameter @uery will ollow the loading o the orm. <rror occurred: This e*ent could not be reconstructed.

#)

Base Handbook

Properties of controls
:nce a orm has been created) it can be illed with *isible controls. .ome controls allow the content o the database to be displayed) or data to be entered into the database. :ther controls are used e6clusi*ely or na*igation) or searching) and or carrying out commands &interaction(. .ome controls ser*e or additional graphical rewor,ing o the orm. %ata entry and %ata dis lay "ontrol
Te6t ield "umeric ield 2ate ield Time ield Currency ield 5ormatted ield %ist bo6 Combo bo6 Chec, bo6 :ptions button ?mage control $attern ield Table control

!se
Te6t entry Fntering numbers Fntering dates Fntering times "umeric entry) pre ormated or currency 2isplay and entry with additional ormatting) or e6ample using measurement units Choosing between se*eral di erent possibilities) also or trans er into the database o *alues other than those displayed .imilar to a list ield) but with only the displayed *alue trans erred) or you can enter new *alues by hand Yes/"o 5ield 1adio buttonP allows you to choose rom a small number o possibilities 2isplay o images rom a database and entry o images into a database *ia a path selection Fntry into a preset mas,P limits the entry possibilities to speci ic character combinations #ni*ersal entry module) which can display a whole table. ?ntegrated into this control are many o the abo*e controls

%esi#n "ontrol
%abel ield !roup bo6

!se
/eading or the orm) description o other controls + rame around) or e6ample) a set o option buttons

)nteraction "ontrol
9utton ?mage 9utton "a*igation bar 5ile selector .pin bo6 .crollbar

!se
9utton with label %i,e a button) but with an additional graphic displayed on it Toolbar *ery similar to the one at the bottom edge o the screen 5or selecting iles) or e6ample to upload in an /T4% ormSnot urther described Can only be used with a macroSnot urther described Can only be used with a macroSnot urther described

3hapter ! 'orms

#,

%efault settin#s for many controls


+s with orms) properties are grouped into three categories' !eneral) 2ata and F*ents. !eneral comprises e*erything that is *isible to the user. The data category speci ies the binding to a ield in the database. The F*ents category controls actions) which can be bound to some macro. ?n a database without macros) this category plays no role.

6eneral tab The name o a control must be uni@ue within the ormSused or access using macros. 2oes the ield ha*e a label; This groups ield and label together.

97

Base Handbook

"onGenabled ields cannot be used and are grayed out. #se ul or control using macros. &F6ample' ? 5ield 1 contains a *alue) 5ield 2 must not contain oneP 5ield 2 is deacti*ated.( #sually CesP in*isible ields can be used as intermediate storage) or e6ample in creating combination ields with macros. .ee Chapter >) 4acros. Ces will e6clude any modi ication o the *alue. This is use ul) or e6ample) or an automatically generated primary ,ey. .ometimes it is use ul to print a page rom a orm rather than a separate report. ?n this case) not all ields may be re@uired to appear. 7ithin a orm) the *ab ,ey is normally used or na*igation. + ield that is readGonly does not need a tab stopP it can be s,ipped. 2oes the ield ha*e a tab stop; /ere the acti*ation se@uence within the orm is speci ied. +nchoring o graphics within a te6t ield. $osition o the top le t corner relati*e to the le t side o the orm. $osition o the top le t corner relati*e to the top o the orm. 7idth o the ield. /eight o the ield. 5ont) ont si0e) and ont e ects can be set here. +lignment. /ere te6t entry is le tG Rusti ied. Vertical alignment' .tandard ^ Top ^ 4iddle ^ 9ottom.

3hapter ! 'orms

9(

9ac,ground color o the te6t ield. 5raming' "o rame ^ 32G%oo, ^ 5lat. ? there is a rame) its color can be set here. /ighlighted te6t loses the highlight when the te6t ield loses ocus. #sed or in ormation to be read by macros. .ee Chapter >) 4acros. +ppears as a tooltip when the mouse is ho*ered o*er the te6t ield. $oints to a help ile) use ul mostly or /T4%. Can be in*o,ed using '( when the ocus is on the ield. In addition= numeric= date fields= etc have the following properties. 7ith testing enabled) only numbers and decimal points may be entered. ?ever does not allow alterations using the mouse wheelP Dhen selected allows such changes when the ield is selected and the mouse is o*er the ieldP >lwa0s means whene*er the mouse is o*er the ield. + spin symbol is incorporated into the right side o the ield. ? a spin arrow is pressed down and held) this determines i the entry in the bo6 should be incremented beyond the ne6t *alue. 2etermines the minimum delay a ter a mouse button press that triggers repetition.

98

Base Handbook

#ata tab

Data field' /ere you create the binding with the table on which the orm is based. <mpt0 string is ?+LL' 7hether an empty string should be treated as &"#%%( or the content simply deleted. <ntr0 re@uired' This condition should match the one in the table. The !#? will prompt or entry i the user has not entered a *alue. 'ilter proposal' 7hen the data is to be iltered) the content o this ield is temporarily stored as a suggestion. Caution A with large contents) this choice can use a lot o storage. Bvents tab

3hanged' This e*ent ta,es place when a control is modi ied and a terwards loses the ocus. *e1t modified' 1e ers to the content) which can in act be te6t) numeric) or whate*er. :ccurs a ter each additional character is entered.
3hapter ! 'orms 9

Dhen receiving focus' The cursor enters the ield. #nder no circumstances must the macro create a message dialog on the screenP clic,ing in such a dialog causes the orm ield to lose the ocus and then reco*er it) triggering the macro again. + loop is created which can only be bro,en by using the ,eyboard. Dhen losing focus' The cursor lea*es the ield. This can lead to the same ,ind o interplay when the handling o the e*ent causes it to recur. Ee0' 1e ers to the ,eyboard. 5or e6ample) a ,ey is pressed when you mo*e through the orm using the Tab ,ey. This causes a ield to recei*e the ocus. Then the ,ey is released. ;ouse' .el Ge6planatoryP These e*ents only ta,es place i the mouse is or was already within the ield &WoutsideW corresponds to the Ra*ascript on4ouse:ut(. 2eset' The orm is emptied o all data. This happens) or e6ample) when starting a new record. 7hen a orm is irst loaded) the two e*ents $rior to reset and >fter resetting occur in succession) be ore the orm is a*ailable or input. +pdating' ? the e*ent is bound to a orm control) update ta,es place when the ocus is lost and Rumps to another orm control) a ter altering the content o the ield. Changes in the orm are accepted and displayed. 7hen a orm is closed) the two e*ents Before updating and >fter updating occur in succession.

$ext field
+s well as the properties set out on page E0) te6t ields can ha*e the ollowing additional properties' 6eneral tab 7hen this *alue is 0) entry is not permitted. #sually the length o the database ield to which the te6t ield corresponds is used here. .hould de ault te6t be put into an empty ield; This te6t must be deleted i any other entry is to be made success ully. $ossible types' .ingleGline ^ 4ultiG line ^ 4ultiGline with ormatting &the last two di er in tabbing beha*iour and) in addition) a pattern ield can not be bound to a database(. The *ertical alignment is not acti*e or multiGline ields. #ni6 or 7indows; This mainly a ects line endings. ?nternally 7indows lines end with two control characters &C1 and %5(. :nly or multiGline ields' /ori0ontal ^ Vertical ^ 9oth.

9!

Base Handbook

+cti*e only or singleGline ields. Changes characters to see only points. #ata tab "othing o signi icance. Bvents tab "othing o signi icance.

*umeric field
?n addition to properties already described) the ollowing properties e6ist' 6eneral tab 4inimum *alue or the ield. .hould agree with the minimum *alue de ined in the table. 4a6imum *alue. .crolling increment when using the mouse wheel or within a spin bo6. Value displayed when a new record is being created. "umber o decimal places) set to 0 or integers. .eparator or thousands) usually a comma. #ata tab There is no chec, on whether a ield can be "#%%. ? there is no entry) the ield will be "#%% and not 0. "o ilter proposal is o ered. Bvents tab The WChangedW e*ent is absent. Changes must be handled using the WTe6t modi iedW e*ent &the word te6t is not to be ta,en literally here(.

%ate field
+s well as the properties described on page E0) the ollowing are to be noted. 6eneral tab 4inimum *alue or the ield) selectable using a dropGdown calendar.

3hapter ! 'orms

9"

4a6imum *alue. .hort orm as 10.02.12 or *arious orms using '/' instead o '.' or '-' in the +merican style. /ere you can enter a literal date but un ortunately not &yet( the current date &Today( at the time the orm is opened. + month calender or selecting dates can be included. #ata tab There is no chec, on whether a ield can be "#%%. ? there is no entry) the ield will be "#%% and not 0. "o ilter proposal is o ered. Bvents tab The WChangedW e*ent is absent. Changes must be handled using the WTe6t modi iedW e*ent &the word te6t is not to be ta,en literally here(.

$ime field
+s well as the properties listed on page E0) the ollowing eatures are a*ailable. 6eneral tab 4inimum *alue or the ield) by de ault set to 0. 4a6imum *alue) by de ault set to 1 second be ore 24'00. .hort orm without seconds) long orm with seconds) and also 12Ghour ormats with +4 and $4. You can set a i6ed time but un ortunately not &yet( the actual time o sa*ing the orm. #ata tab There is no chec, on whether a ield can be "#%%. ? there is no entry) the ield will be "#%% and not 0. "o ilter proposal is o ered. Bvents tab The WChangedW e*ent is absent. Changes must be handled using the WTe6t modi iedW e*ent &the word te6t is not to be ta,en literally here(.

9#

Base Handbook

"urrency field
?n addition to the properties already listed on page E0) the ollowing eatures are a*ailable' 6eneral tab 4in. *alue) 4a6. *alue) ?ncrement) 2e ault *alue) 2ecimal places) and Thousands separator. correspond to the general properties listed on page EB. ?n addition to these) there is only' The symbol is displayed but not stored in the table that underlies the orm. .hould the symbol be placed be ore or a ter the number; #ata tab There is no chec, on whether a ield can be "#%%. ? there is no entry) the ield will be "#%% and not 0. "o ilter proposal is o ered. Bvents tab The WChangedW e*ent is absent. Changes must be handled using the WTe6t modi iedW e*ent &the word te6t is not to be ta,en literally here(.

'ormatted field
?n addition to the properties listed on page E0) the ollowing eatures are o ered' 6eneral tab 4inimum and ma6imum *alues) and the de ault *alue) depend on the ormatting. 9ehind the button or 5ormating is a le6ible ield that ma,es most currency and numeric ields unnecessary. #nli,e a simple currency ield) a pattern ield can show negati*e sums in red. The button to the right with the three dots pro*ides a choice o numeric ormats) as you usually do in Calc. +mong the numeric ormats can be seen) alongside 2ate) Time) Currency or normal numeric ormat) possibilities or using ields with a measurement unit such as 9B &see 5igure 2E(. .ee also the general /elp on numeric ormat codes. #ata tab "othing special to report. Bvents tab The WChangedW e*ent is absent. Changes must be handled using the WTe6t modi iedW e*ent &the word te6t is not to be ta,en literally here(.

3hapter ! 'orms

99

'igure 89: 'ormatted field with general numeric options

List box
7hen a list bo6 is created) the %ist 9o6 7i0ard appears by de ault. This automatic appearance can be switched o i re@uired using the 7i0ards :n/: button &shown in 5igure 24(. 0iPard

9)

Base Handbook

The orm is already de ined. ?t is bound to a *able named %oans. + list bo6 shows the user di erent data rom what is actually transmitted into the table. This data usually comes rom another table in the database) and not rom the table to which the orm is bound. The %oans table is supposed to show which 1eader has borrowed which 4edia. /owe*er this table does not store the name o the reader but the corresponding primary ,ey rom the 1eader table. ?t is there ore the 1eader table that orms the basis or the list bo6.

The &urname ield rom the 1eader table should be *isible in the list bo6. This ser*es as the 2isplay ield.

The 2eader:.D ield occurs in the %oan table which underlies the orm. This table is described here as the Balue table. The primary ,ey ?2 rom the 1eader table must be bound to this ield. The 1eader table is described here as the List table. The list bo6 has now been created complete with data and de ault con iguration and is ully unctional. ?n addition to the properties listed on page E0) the ollowing eatures are a*ailable.

3hapter ! 'orms

9,

6eneral tab The list entries ha*e already been set using the 7i0ard. /ere you could add urther entries that are not rom any table in the database. %ist entries here means the *isible entries) not those that the orm will transmit to the table. ? the ield is not speci ied as dropG down) scroll arrows will appear on the right side o the list bo6 when the orm is loaded. The list ield then automatically becomes a multiGline ield) in which the actual *alue selected is highlighted. ? the ield is dropGdown) this property gi*es the ma6imum *isible number o lines. ? the content e6tends o*er more lines) a scrollbar appears when the list drops down. Can more than one *alue be selected; ?n the abo*e e6ample) this is not possible since a oreign ,ey is being stored. #sually this unction is not used or databases) since each ield should only contain one *alue. ? necessary) macros can help in the interpretation o multiple entries in the list ield. +s the deacti*ated button ma,es clear) a de ault selection ma,es little sense in the conte6t o a binding with a database table) as created by the %ist 5ield 7i0ard. ?t could well be the case that the record corresponding to the de ault selection in the e6ample table 1eaders is no longer present. #ata tab ?n addition to the usual data properties Data field and .nput re@uired) there are signi icant properties which a ect the binding between the displayed data and the data to be entered into the table that underlies the orm. *0pe of list contents' Valuelist ^ Table ^ Duery ^ .D% ^ .D% _"ati*e` ^ Table ields List contents Baluelist' ? list entries ha*e been created under 6eneral) the corresponding *alues to be stored are entered here. The list contents are loaded with indi*idual items separated by .%Ct D E(te/. The List content ield then shows them as "V)&=eE"F"V)&=e8"F"V)&=eG" ; The Bound 'ield property is inactive.

)7

Base Handbook

List contents *able' /ere one o the database tables can be selected. /owe*er this is seldom possible as it re@uires the content o the table to be so structured that the irst table ield contains the *alues to be displayed in the list ield) and one o the ollowing ields contains the primary ,ey which the table underlying the orm uses as a oreign ,ey. The position o this ield within the table is speci ied in Bound 'ield) where the 9umbering begins with . for the first field of the database table. 9ut this 0 is reser*ed or the displayed *alue) in the abo*e e6ample the .urname) while the 1 re ers to the ?2 ield. List contents Auer0' /ere a @uery is irst created separately and stored. The creation o such @ueries is described in Chapter B) Dueries. #sing the @uery) it is possible to mo*e the ?2 ield rom the irst position in the underlying table to the second position) here represented by the bound ield 1. List contents &AL' The %ist 9o6 7i0ard ills this ield. The @uery constructed by the 7i0ard loo,s li,e this' The @uery is the simplest possible. The .urname ield occurs at position 0) the ?2 ield at position 1. 9oth are read rom the 1eader table. +s the bound ield is 5ield 1) this .D% ormula wor,s. /ere should be added ORDER BY "L)stN)*e" A C. .o you ha*en=t to scroll to long through the list to ind somebody. +n additional problem might be) that Last?ame could be the same or more than one reader. .o 'irst?ame must be added in the *iew o the list bo6. 7hen there are readers with the same Last?ame and the same 'irst?ame) the primary ,ey .D must also be shown. .ee Chapter B) Dueries) or in ormation on how this wor,s. List contents &AL F?ativeG' The .D% ormula is entered directly) not using the 7i0ard. 9ase does not e*aluate the @uery. This is suitable when the @uery contains unctions that might perhaps not be understood by the 9ase !#?. ?n this case the @uery is not chec,ed or errors. 4ore about direct ?(+ -ode can be ound in Chapter B) Dueries. List contents tablefields' /ere 'ield names rom a table are listed) not their content. 5or the 1eader table) the %ist contents would be W?2W) W!i*en nameW) W.urnameW) W%oc,W) W!enderL?2W. Bvents tab ?n addition to the standard e*ents) the ollowing e*ents are a*ailable' <1ecute action' ? a *alue is chosen by the ,eyboard or the mouse) the list bo6 e6ecutes this action. .tem status changed' This could be the change o the displayed content o a list bo6 through the use o the dropGdown button. ?t could also be a clic, on the dropGdown button o the ield. <rror occurred' #n ortunately) this e*ent cannot be reconstructed or list bo6es.

3hapter ! 'orms

)(

"ombo box
+s soon as a combo bo6 is created) a 7i0ard appears by de ault) Rust as with a list bo6. This automatic beha*ior can be switched o i necessary using the 7i0ards :n/: button &see 5igure 24(. Combo bo6es write the selected te6t directly into the table underlying the orm. There ore the ollowing e6ample shows both the table lin,ed to the orm and the one selected or the control as the 1eader table. 0iPard

+gain the orm is prede ined) this time with the 1eader table. +s the data to be displayed in the combo bo6 is also to be stored in this table) the source selected or the data or the list is li,ewise the 1eader table.

?n the 1eader table the 5irst"ame ield occurs. This should be displayed in the combo bo6.

)8

Base Handbook

?n a database) there seems to be little point in not storing the *alue o a combo bo6 within a ield. 7e want to read gi*en names rom the 1eader table) and also to ma,e them a*ailable or new readers) so that new records do not need to be created or a gi*en name that already e6ists in the database. The combo bo6 shows the irst name) and te6t input is not necessary. ? a new *alue does need to be entered) this can be done easily in a combo bo6) as the bo6 shows e6actly what is going into the underlying table or the orm. ?n addition to the properties shown on page E0 and described or list bo6es) the ollowing eatures are a*ailable. 6eneral tab 2uring entry o new *alues) a list o matching *alues &i any( is displayed or possible selection. #ata tab

The data ields con orm to the e6isting de ault settings and the settings or a list bo6. The .D% command howe*er shows a special eature' ')'&( ,+ (+-&( "First-ame" FROM "Reader" +dding the DI TINCT ,eyword ensures that duplicate gi*en names are shown only once. /owe*er) creation using the 7i0ard once more ma,es it impossible or the content to be sorted. Bvents tab The e*ents correspond to those or a list bo6.

3hapter ! 'orms

"heck box
The chec, bo6 appears immediately as a combination o a chec, bo6 ield and a label or the bo6. ?n addition to the properties described on page E0) the ollowing eatures are a*ailable. 6eneral tab The label or this bo6 appears by de ault to the right o the bo6. ?n addition you can bind it to a separate label ield. /ere) dependent on the choice in the TriGstate ield) up to three possibilities are a*ailable' ?ot selected ^ &elected ^ ?ot defined. ?ot defined corresponds to a ?+LL entry in the table underlying the orm. 9y de ault) the label is not bro,en up. The label is truncated i the ield is not big enough. /ere you can speci y a graphic instead o or in addition to the label. You should note that these graphics are not bound into the H.odb document by de ault. 5or small graphics) it is use ul to embed the graphic and not lin, it. ? you ha*e chosen to use a graphic) its alignment with the label can be set here. 9y de ault) chec,bo6es ha*e only two states' &elected &Value' 1( and ?ot selected &Value' 0(. 7ith TriG state) a de inition o <mpt0 field &"#%%( is added. #ata tab

)!

Base Handbook

The chec, bo6 can be gi*en a re erence *alue. /owe*er only the *alues o 1 & or :n( or 0 & or : ( can be trans erred to the underlying data ield &chec, bo6es act as ields or the choice o Yes and "o(. Bvents tab The ields WChangedW) WTe6t modi iedW. W9e ore updatingW and W+ ter updatingW are all absent. +dditional ields or a chec, bo6 are WF6ecute actionW &see %ist bo6( und W?tem status changedW &corresponds to WChangedW(.

O tion button
The option button is similar to the chec, bo6 described abo*e) e6cept or its general properties and its e6ternal &round( orm. 7hen se*eral option buttons in the orm are lin,ed to the same table ield) only one o the options can be selected. 6eneral tab The option button is designed to be used in groups. :ne o se*eral options can then be selected. That is why a !roup name appears here) under which the options can be addressed. #ata tab .ee under Chec, bo6. /ere) howe*er) re erence *alues that are entered are actually trans erred to the data ield. Bvents tab .ee under Chec, bo6.

)ma#e control
+ image control handles the entry and display o graphical material in the database. The underlying data ield must be a binary ield. Fntry into a image control ta,es place either by a doubleGclic, with the mouse to open a ile selection dialog) or a rightGclic, to choose whether an e6isting graphic is to be deleted or replaced. + graphical control by de ault has no Tab stop. ?n addition to the properties described on page E0) the ollowing eatures are a*ailable. 6eneral tab The graphic selected here is only shown inside the control) while the orm is being edited. ?t has no signi icance or later input.

3hapter ! 'orms

)"

?o' The image will not be itted to the ield. ? it is too big) the ield will show a window into the image. The image is not distorted. Eeep ratio' The image is itted to the control but not distorted &aspect ratio preser*ed(. >utom. &i/e' The image is itted to the control and may be shown in a distorted orm. #ata tab "othing urther to report. Bvents tab The e*ents WChangedW) WTe6t modi iedW) W9e ore updatingW and W+ ter updatingW are missing..

+attern field
+n input mas, is used to control input into the ield. Characters are preGspeci ied or particular positions) determining the properties o entered characters. The preset characters are stored along with the entered ones. ?n addition to the properties described on page E0) the ollowing eatures are a*ailable. 6eneral tab This determines what characters can be entered. This is what the orm user sees. The ollowing content is ta,en rom %ibre: ice /elp' The length o the edit mas, determines how many characters may be entered. ? the user=s entry does not match the mas,) the entry is reRected on lea*ing the control. The ollowing characters are a*ailable or de ining the edit mas,. "haracter %
a + c C " 6 M

Meanin# + te6t constant. This position cannot be edited. The actual character is displayed at the corresponding position in the literal mas,.
1epresents any o the letters aG0/+Ga. Capital letters are not con*erted into lower case. 1epresents any o the letters +Ga. ? lowerGcase letters are entered) they will automatically be con*erted to upper case. 1epresents any o the characters aG0/+Ga plus the digits 0G>. Capital letters are not con*erted into lower case. 1epresents any o the letters +Ga plus the digits 0G>. ? lowerGcase letters are entered) they will automatically be con*erted to upper case. :nly the digits 0G> can be entered. +ll printable characters are allowed. +ll printable characters are allowed. ? lowerGcase letters are entered) they will automatically be con*erted to upper case.
Base Handbook

)#

.o) or e6ample) you can de ine the literal mas, as WLL/LL/2012W and the edit mas, as W""%""%%%%%W) to allow the user to enter our characters only or a date. #ata tab "othing urther to report. Bvents tab The WChangedW e*ent is absent.

$able control
This is the most comprehensi*e control. ?t pro*ides a table) which can then be pro*ided with controls or indi*idual columns. This not only allows the actual data to be *iewed during input) but also the pre*iously entered data) without the need to use the "a*igation bar to scroll through the records. "ot e*ery ield that is possible in a orm can be selected or a table control ield. $ush buttons) image buttons and option buttons are not a*ailable. The Table Control 7i0ard assembles in a window the ields that will appear a terwards in the table.

?n the control the %oans table is a*ailable or editing. ?n addition to the ?2 &primary ,ey( ield and the 4ediaL?2L9C ield &entry o media using a barGcode scanner() all ields are to be used in the control. The pre*iously created table control must now be urther de*eloped) to allow entry into the %oans table. 5or ields such as 2eader:.D or ;edia:.D) it would be more use ul to be able to choose the reader or the media directly) rather than a number representing the reader or media. 5or this purpose) controls such as list bo6es can be placed within the table control. This is declared later. The ormatting o the <1tension ield with two decimal places was certainly not intended.

3hapter ! 'orms

)9

'igure 8): Output of the *able 3ontrol Di/ard ?n addition to the properties listed on page E0) the ollowing eatures are a*ailable. 6eneral tab /eight o indi*idual lines. 7ith no *alue here) the height is automatically adRusted to the ont si0e. 4ultiGline te6t ields are then shown as single lines to be scrolled. +s with tables) the lower edge o the control shows the record number and na*igation aids. 9y de ault there is a record mar,er on the le t edge o the control. ?t indicates the current record. You can use the record mar,er to access the delete unction or the whole record. #ata tab .ince this is a ield that contains no data itsel but manages other ields) there are no data properties. Bvents tab The WChangedW and WTe6t modi iedW e*ents are missing. The WFrror occurredW e*ent is added.

Label field
?n addition to the properties described on page E0) the ollowing eatures are a*ailable. 6eneral tab 9y de ault a label is not wrapped. ? it is too long or the ield) it is truncated. Caution' word wrapping does not recogni0e spaces) so i the ield is too small) a brea, can occur within a word. #ata tab "one.

))

Base Handbook

Bvents tab The label ield reacts only to e*ents that are connected with the mouse) a ,ey or the ocus.

(rou box
+ group bo6 graphically groups se*eral controls and pro*ides them with a collecti*e label. ? a group bo6 is created with 7i0ards acti*e) the 7i0ard proceeds rom the assumption that se*eral option buttons will occur together within this rame.

This orm is based on the 1eader table. 7e are dealing with the choice o gender. The entries are the labels o the option buttons.

/ere the de ault option is W emaleW. ? there is to be no de ault ield) the de ault entry in the underlying table is ?+LL.

3hapter ! 'orms

),

The 7i0ard gi*es the option buttons separate *alues by de ault) here 1 or emale and 2 or male. These *alues correspond to the e6amples o primary ,ey ields in the !ender table. The *alue selected by clic,ing an option button is trans erred to the %ender:.D ield o the ormKs underlying table 1eaders. ?n this way the 1eaders table is pro*ided with the corresponding oreign ,ey rom the !ender table by using the option button.

The option button group is gi*en a group bo6 & rame( with the label !ender.

? emale is selected in the acti*e orm) male is deselected. This is a characteristic o option buttons that are bound to the same ield in the underlying table. ?n the e6ample shown abo*e) the option buttons replace a twoGelement list bo6. ?n addition to the properties described on page E0) the ollowing eatures are a*ailable.
,7 Base Handbook

6eneral tab The label can be changed rom its de ault *alue. +t present the rame properties &%ine thic,ness) line color( cannot be changed but you can change the ont ormatting. #ata tab "one) since this control ser*es only or *isual grouping o ields. Bvents rab The group bo6 reacts to e*ents in*ol*ing the mouse) a ,ey) or the ocus.

+ush button
?n addition to the properties described on page E0) the ollowing eatures are a*ailable. 6eneral tab %abel on the button. The button recei*es the ocus when it is clic,ed. ? Yes) the button can be shown pressed in. The button state is shown as or a switch. 7hen you press it a second time) it shows an unpressed button. +cti*e) when Toggle is set to Hes. &elected corresponds to the pressedGin button. 7ord wrapping i the button is too narrow. + *ariety o actions similar to those or the na*igation bar are a*ailable. /T4%' 5ile to be called up with this button. :nly or /T4% orms' The targetG rame & rame arrangement or di erent /T4% pages( in which the ile should be opened. The de ault button is ramed when this is set to Hes. 7hen there are se*eral alternati*e buttons on a orm) the one most o ten used should ha*e this characteristic. ?t is acti*ated by pressing the Fnter ,ey) when no other action needs to depend on this ,ey. :nly one button on the orm can be the de ault button.

3hapter ! 'orms

,(

.hould a graphic appear on the button; :nly acti*e when a graphic has been selected. .peci ies the alignment o the graphic to the te6t. #ata tab "one. + button only carries out actions. Bvents tab W+ppro*e actionW) WF6ecute actionW and W?tem status changedW.

)ma#e button
?n addition to the properties already described on page E0) the ollowing eatures are a*ailable. 6eneral tab .imilar to a normal button. /owe*er this button has no te6t and the button itsel is not *isible. You see only a rame around the graphic. 9y de ault) an image button has no tab stop. Caution' at the time o writing) hardly any actions wor, with this button. ?t is practically only usable with macros. #ata tab "oneP this control only carries out actions. Bvents tab W+ppro*e actionW and all e*ents in*ol*ing the mouse) a ,ey) or the ocus.

*avi#ation bar

'igure 8,: ?avigation bar control The standard 5orm "a*igation bar is inserted into orms at the lower edge o the screen. The insertion o this toolbar can cause a brie rightward shi t o the orm as it builds up on the screen. This can be distracting in cases where the na*igation bar is switched o again or some parts o the *isible orm) or e6ample when there are sub orms or more than one orm in the *isible orm. 9y contrast) a na*igation bar control that is part o the orm) separate rom the corresponding items) ma,es it clear through which items you na*igate with the toolbar. The orm or %oans) or e6ample) needs to search irst through the readers and then show the media loaded to the reader. The na*igation bar control is positioned near the reader) so the user notices that the na*igation bar is used or the reader and not or the media loaned to the reader. The standard 5orm "a*igation bar ma,es a*ailable the buttons shown in 5igure 30. The na*igation bar control shows the same buttons e6cept those or 5ind 1ecord) 5ormG9ased 5ilters and 2ata source as Table.

,8

Base Handbook

'igure 7: ?avigation buttons ?n addition to the properties listed on page E0) the ollowing eatures are a*ailable or the "a*igator 9ar control. 6eneral tab The icon si0e is adRustable. ?n addition you can choose which groups are displayed. These are shown in 5igure 2> rom le t to right using a *ertical line as a group separator' $ositioning) "a*igation) +cting on a record) and groups o commands or 5iltering and .orting. #ata tab "one) as this control only carries out actions. Bvents tab +ll e*ents that in*ol*e the 4ouse) a ,ey) or the ocus.

3hapter ! 'orms

?ndependent o this orm control) the insertable navigation bar naturally continues to e6ist with the same items as the abo*e igure. This insertable na*igation bar pro*ides additionally the general record search) the form-based filter and the display o the orm=s underlying data source in table view abo*e the orm. ? you are wor,ing not Rust with a orm but with sub orms and ancillary orms) you must be care ul that this insertable na*igation bar does not disappear as you switch orms. That creates a disturbing e ect on the screen.

Multi le selection
? you use the .elect icon &5igure 24( to select a large region or se*eral elements o a orm) the ollowing modi ications may be carried out &see 5igure 31(.

'igure (: %eneral properties of form fields in a multiple selection You should not alter the name. That would cause all the selected elements suddenly to ac@uire the same name. ?t would ma,e inding indi*idual elements using the 5orm "a*igator di icult) and management o the orm by using named controls in macros impossible. 4ultiple selection is more use ul or changing the ont) the height or the bac,ground color o controls. "ote that changing the bac,ground color a ects the labels as well. ? you want to alter only the labels) hold down the 3ontrol ,ey and clic, these controls directly or in the "a*igator) or rightGclic, on a ield to call up the control properties. "ow the choice o properties that you can change is greater as you are dealing only with similar ields. You can change anything here that is a*ailable in a label ield. The possibilities o multiple selection depend there ore on the choice o ields. You can simultaneously change controls o the same ,ind that ha*e all the properties that e6ist or a single instance.

,!

Base Handbook

A simple form completed


+ simple orm has orm controls or writing or reading records rom a single table or @uery. ?ts construction is shown by the ollowing e6ample.

Desktop

5orm
Control ield 1 Control ield 2 Control ield 3 Control ield ...

The e6ample o a simple orm or library loans is shown here using se*eral *ariants. The @uic, way to use the 5orm 7i0ard is described in Chapter <) !etting .tarted with 9ase) in the %etting &tarted with LibreOffice guide. /ere we describe the creation in 2esign View.

The heading or the orm was created using a label ield. The ont was changed. The label ield is anchored to a paragraph in the top le t corner o the document. #sing the conte6t menu o the label ield) a orm was created that was lin,ed to the %oans table &see I5orm propertiesJ on page CC(. The page has also been gi*en a uni ormly colored bac,ground.

,ddin# #rou s of fields


+ @uic, *ariant or direct entry o ields with labels is to use the >dd 'ield unction.

This unction) a*ailable on the 5ormula 2esign toolbar &see 5igure 22() allows all ields o the underlying table to be selected.

3hapter ! 'orms

,"

2oubleGclic, on the ields to insert them into the orm as a group with labels &un ortunately all on the same spot(. The group needs to be separated out so that the orm e*entually loo,s li,e the ollowing illustration. 5or a better *iew) all unnecessary toolbars ha*e been remo*ed rom the window) which has also been compressed so that not all elements o the "a*igation bar are *isible. +ll ields ha*e been selected e6cept ;edia:.D:B3) which is designed to be used only with a barcode scanner.

'igure 8: &imple form made b0 using >dd 'ield 5or each table ield) an appropriate orm control has been automatically selected. "umbers are in numeric ields and are declared as integers without decimal places. 2ate ields are represented correctly as date controls. +ll ields ha*e been gi*en the same width. ? a graphical control had been included) it would ha*e been gi*en a s@uare ield.

,d-ustin# field ro ortions


7e can now do some creati*e things) including adRusting the length o the ields and ma,ing the dates into dropGdown ields. 4ore important still is or the ;edia:.D and the 2eader:.D ields to be made more userG riendly) unless e*ery library user has a library ?2 card and e*ery medium is supplied with an ?2 on accession. That will not be assumed in what ollows. To adRust indi*idual ields) we must edit the group. This can be done with a rightGclic, on the group and then ollowing the conte6t menu &5igure 33(. 5or uture wor,) it will be clearer i we use the 5orm "a*igator.

,#

Base Handbook

'igure

: 'orm controls: editing the group

The 5orm "a*igator displays all the elements o the orm with their labels. 5or controls) the names are ta,en directly rom the names o the ields in the underlying table. The names o the labels ha*e the su i6 Label. + clic, on ;edia:.D selects this ield &5igure 34(. 1ightGclic, to replace the selected ield with a di erent type o ield) using the conte6t menu &5igure 3B(.

'igure !: &electing form controls directl0 using the 'orm ?avigator

3hapter ! 'orms

,9

'igure ": 2eplacing one kind of control b0 another using the 'orm ?avigator This replacement is carried out or the ;edia:.D and 2eader:.D controls.

The change is made *isible in the 5orm "a*igator by the change in the accompanying icon.

,)

Base Handbook

The .D% @uery or the list ield can now be created through the graphical user inter ace by clic,ing on the button at the right. This is carried out automatically when a list bo6 is created directly) but not when it is ormed by con*ersion rom another type o control. 5or the .D% command) see Chapter B) Dueries. .ince the list bo6es are to be made dropGdown) the ollowing de ects can be corrected at the same time'

T T T

The labels or the list bo6es should be ;edia instead o ;edia:.D and 2eader instead o 2eader:.D. The .D control should be declared as readGonly. +ny ields which are not absolutely necessary or issuing loans or a new medium do not need a tab stop. 7ithout it) the orm can be tra*ersed much aster. ? necessary) the tab stop can also be adRusted using the acti*ation se@uence &see page E0(. :nly the ;edia) 2eader and Loan date ields must be accessible in all cases using the *ab ,ey. ? the orm is intended or carrying out loans) it is unnecessary and also con using or returned media to be displayed. 4edia with a return date should be iltered out. ?n addition) the display order could be sorted by 1eader) so that media on loan to the same person are displayed successi*ely. .ee the note on I5orm propertiesJ on page CC. /owe*er there is a problem here in that readers can be sorted only by ?2) not alphabetically) because the table underlying the orm only contains the ?2.

,ddin# sin#le fields


The addition o single ields is a bit more complicated. The ields must be selected) dragged onto the orm sur ace) and the appropriate ield rom the underlying table speci ied. ?n addition) the type o ield must be correctly chosenP or e6ample) numeric ields ha*e two decimal places by de ault. :nly when creating list bo6es does the 7i0ard come into play) ma,ing it easier or a no*ice to carry out the steps or creating correct ieldsSup to a point. 9eyond that point) the 7i0ard ceases to meet re@uirements because'

T T

The entries are not automatically sorted. Combining se*eral ields in the list bo6 content is not possible.

/ere again we need to ma,e retrospecti*e impro*ements) so that the re@uired .D% code can be created @uite @uic,ly using the builtGin @uery editor. 7hen adding single controls) the ield and its label must be e6plicitly associated &see I2e ault settings or many controlsJ on page E0(. ?n practice it could be better i you do not associate ields with the labels. .o you must not choose Bdit 6roup be ore changing the properties o a ield.

3hapter ! 'orms

,,

$able control
The use o the Table 7i0ard to create a table control has already been described on page <E. ?t has howe*er some de ects which need to be impro*ed'

T T

The ;edia:.D and 2eader:.D ields must become list bo6es. "umeric ields must be stripped o their decimal places) since the 7i0ard always speci ies two decimal places or numbers.

Changing ields within the table control is not possible using the same method as described or other controls. ?n the "a*igator) the description o ields ends with the table control. The "a*igator ,nows nothing about the controls that lie within the table control) re erring to ields in the underlying table. This e@ually applies later) when attempts are made to access the ields using macros. They cannot be accessed by name.

The controls within the table control are called columns. #sing the conte6t menu) it is now possible to replace one type o ield by another. /owe*er the whole range o types is not a*ailable. There are no push buttons) option bo6es) or graphical controls.

The properties o the ields are hidden in the conte6t menu behind the concept o columns. /ere) or e6ample) the numeric ield <1tension can be changed so that no decimal places are shown.

(77

Base Handbook

+lso the de ault minimum *alue o A1)000)000.00 hardly ma,es sense or a loan e6tension. The number should always remain small and positi*e. +s soon as the properties o a column are called up) you can select another column without shutting the properties dialog. ?n this way you can wor, on all the ields) one a ter another) without ha*ing to sa*e in between. Fnd by sa*ing the entire orm) and inally the database itsel . The properties o the ields built into a table control are not so comprehensi*e as or those outside. The ont) or e6ample) can be set only or the entire table control. ?n addition) you do not ha*e the option o s,ipping indi*idual columns by remo*ing their tab stops.
You can mo*e through a orm using either the mouse or the *ab ,ey. ? you tab into a table control) the cursor will mo*e one ield to the right or each additional tabP at the end o the line) it will mo*e bac, to the irst ield o the ne6t record in the table control. To e6it the table control) use 3trl4*ab.

$ip

The order o the columns can be changed by dragging the column header'

? this is done in orm design *iew) it is permanent. + temporary change in order can be carried out during data entry by using the same method. ? only certain ields should be *isible during use) you can use se*eral di erent table controls in the orm) as the *ab is captured by de ault by each table control. The orm shown in 5igure 3C is or the loan o media. :nly the ields immediately necessary are shown in the upper table control. The lower one shows all the ields) so that it is apparent which person and medium the return is or.

'igure #: > form with multiple table controls

3hapter ! 'orms

(7(

This igure shows an aesthetic ailing that needs urgent attention. ?n the upper table control) the same medium sometimes occurs more than once. This happens because the table also shows media that ha*e been returned earlier. There ore the data needs to be iltered to show only the loans. 1ecords with a return date should not appear. This iltering is possible either by a @uery or directly using the orm properties. ? it is done using the orm properties) the ilter can be temporarily switched o during input. 5iltering using a @uery is described in Chapter B) Dueries. /ere we describe how to do it using orm properties.

The iltering is carried out using the button with the three dots) which opens the dialog shown below. You can also enter the ilter directly into the 'ilter te6t ield i you ,now the .D% coding.

#sing the !#?) you can now select the ield named 2eturn:Date. ?t will show only the records or which the ield is empty) where IemptyJ stands or the .D% designation "#%%. The cleanedGup orm &shown in 5igure 3E( now loo,s rather simpler. : course there is still room or impro*ement) but compared with the earlier orm) this *ersion has a clear ad*antage in that all the media are *isible at a glance. The processing o data using table controls is similar to using an actual table. + rightGclic, on the record header o an e6isting record causes it to be deleted) and an entry can be canceled or sa*ed in the case o new records. 7hen you lea*e a line) the record is automatically sa*ed.

(78

Base Handbook

'igure 9: >mended form 7e can still impro*e the %oan o 4edia orm in a number o ways.

T T

?t would be nice i selecting a reader in one part o the orm caused the media on loan to this reader to be displayed in another. ?n the table shown abo*e) you can see a lot o records that are not necessary because these media are already on loan. The table was created to allow loans to be made) so it would be better i only an empty page appeared) which could then be illed with the new loan.

.uch solutions are a*ailable using urther orms that are hierarchically arranged and ma,e possible separate *iews o the data.

-ain forms and subforms


+ sub orm lies within a orm li,e a orm control. %i,e a orm control) it is bound to data rom the main orm. /owe*er its data source can be another table or a @uery &or a .D% command(. The important thing or a sub orm is that its data source is somehow lin,ed to the data source o the main orm.

Desktop

5orm
Control ield 1 Control ield 2 Control ield 3 Control ield ...

.ub orm
Control ield 1 Control ield 2 Control ield 3 Control ield ...

3hapter ! 'orms

(7

Typical table structures that lend themsel*es to use as sub orms are tables with a oneGtoGmany relationship &see Chapter 3) Tables(. The main orm shows a table with records to which many dependent records in the sub orm can be lin,ed and displayed. 5irst we will use the relationship o the 1eader table to the %oan table &see Chapter 3) Tables(. The 1eader table will orm the basis or the main orm and the %oan table will be reproduced in the subG orm.

/ere the main orm is lin,ed to the 1eader table. To speed up the search or readers) the table is sorted alphabetically. 7e will do without a na*igation bar) since the content o the sub orm would come between the main orm and the na*igation bar. ?nstead we will use the builtGin orm control &5igure 2>(.

1ightGclic, on the main orm in the 5orm "a*igator to use the conte6t menu to create a new orm. :nce again this orm has the de ault name o 5orm) but it is now an element in the sub older o the main orm.

(7!

Base Handbook

The properties o the sub orm must now be set up to gi*e it the right data source) in order to reproduce the data or the correct reader.

The %oans table is chosen or the sub orm. 5or the ilter we speci y that the 1eturn date ield should be empty &WRet=/(_D)te" I NULL(. This pre*ents any media that ha*e already been returned rom appearing. The records should be sorted by loan date. The ascending sort shows the medium on loan or the longest period at the top. Link master fields and Link slave fields are used to create a lin,age to the main orm) in which the sub orm lies. The button with three dots shows once again that a help ul dialog is a*ailable or creating these.

#nder Loans) the ields in the %oans table are shown) under 2eaders those o the 1eader table. The 2eader:.D rom Loans should be set as e@ui*alent to the .D rom the 1eader table. +lthough this lin,age has already been created in the database using $ools 5 )elationships &see Chapter 3) Tables() the unction that lies behind the .uggest button in this dialog does not re erence this and would suggest that the irst oreign ,ey in the %oan table) namely ;edia:.D)

3hapter ! 'orms

(7"

should be lin,ed with .D rom the 1eader table. The 5orm Creation 7i0ard sol*es this better by reading the relation rom the relationship o the database.

The chosen lin, between the table or the sub orm and the table or the main orm is now speci ied in terms o ields rom the tables. To create a table control or the main orm) we must now select the main orm in the 5orm "a*igator. Then) i the Table Control 7i0ard is enabled) it will show the ields a*ailable in the main orm. 7e deal with the sub orm in a similar way. :nce the table controls ha*e been set up) we need to carry out the modi ications already discussed when creating the simpler orm'

T T T T T

1eplacing the numeric ield ;edia:.D in the sub orm with a list bo6. 1enaming the ;edia:.D ield ;edia. 4odi ying the numeric ields to a ormat without decimal places. %imiting the minimum and ma6imum *alues. 1enaming other ields) to sa*e space or to add nonG+.C?? characters which should not be used in ield names in database tables.

.ort and ilter unctions are supplemented or the main orm by adding a na*igation bar. The other ields on the na*igation bar are not needed) as they are mostly a*ailable rom the table control &record display) record na*igation( or else carried out by mo*ement through the table control &data storage(. The inal orm might loo, li,e the igure below.

'igure ): 'orm consisting of a main form 5above6 and a subform 5below6.

(7#

Base Handbook

? a reader is now selected in the main orm) the sub orm will show the media on loan to that reader. 7hen an item is returned) it continues to appear on the orm until the orm itsel is re reshed. This occurs automatically when another record is loaded into the main orm. ? the original reader is selected again) returned media are no longer displayed. This delayed updating is actually desirable in this case) as it allows one to inspect the media currently lying on the library counter and see at once whether these ha*e been registered. This orm structure is signi icantly easier to use than the pre*ious one with only a single orm. /owe*er there are still details that can be impro*ed'

T T T T T

4edia and loan dates might be changed when the media is to be loaned out or longer. Changing the media date might ma,e it impossible to trace which item is still a*ailable in the library and which is on loan. Changing the loan date could lead to errors. 1ecall notices could not be *eri ied. ? a reader record is not selected by clic,ing on the record header at the le t) only the little green arrow on the header shows which record is currently acti*e. ?t is @uite possible that the acti*e record will be scrolled right out o the table control window. ?nstead o the te6t ILoaned ;edia of the chosen 2eaderJ) it would be better to ha*e the readerKs name. ?t is possible to loan out the same medium twice without it ha*ing been returned. ?t is possible to delete the record or an item on loan @uite easily. 2ata can be changed or deleted in the main orm. This can be use ul or small libraries with little public tra ic. /owe*er when things become hectic at the loans counter) editing o user data should not ta,e place at the same time as issuing loans. ?t would be better i new users could be registered but e6isting user data le t untouched. 5or libraries) this applies e@ually to deletions or complete name changes.

5irst let us impro*e the selection o readers. This should protect us rom changes to the loan records. + simple solution would be not to allow any modi ication e6cept the entry o new records. This still re@uires a search unction when a reader wishes to borrow an item. ?t would be better to use a list bo6 to ind the reader and carry out the issue and return operations in separate table controls. 5or the main orm we need a table) into which the list bo6 can write a *alue lin,ed to this table. The table re@uires an integer ield and a primary ,ey. ?t will always contain only one record) so the primary ,ey ield ?2 can sa ely be declared as Tiny ?nteger. The ollowing table named 5ilter should there ore be created. $able name. 'ilter 'ield name
?2 ?nteger

'ield ty e
Tiny ?nteger) $rimary ,ey ?nteger

The table is gi*en a primary ,ey with the *alue 0. This record will be repeatedly read and rewritten by the main orm.

3hapter ! 'orms

(79

The main orm is based on the 5ilter table. ?t will Rust read the *alue rom the table which is associated with the primary ,ey &.D( o 0. "o data will be addedP the current record will Rust be repeatedly rewritten. +s only edits o a single record are allowed) a na*igation bar would be super luous.

This main orm is lin,ed to the sub orm in such a way that the *alue o the ?nteger ield in the 5ilter table is the same as the *alue o the 2eader:.D ield in the %oan Table. The sub ormKs properties are unchanged rom the *ersion shown abo*e. 9e ore we create a list bo6 in the main orm) we must switch o the wi0ards. The list bo6 7i0ard only allows you to create a bo6 that shows the content o a single ieldP it would be impossible to ha*e surname and gi*en name and an additional number in the display area o a list bo6. +s in the simpler orm) we now enter or the list bo6 contents &urnameI %iven name C .D ?r. The list bo6 transmits the ?2 to the underlying table.

(7)

Base Handbook

"e6t to the list bo6) a button is created. This button is actually part o the sub orm. ?t ta,es o*er two unctions' sa*ing the record in the main orm and updating the table in the sub orm. ?t is good enough to entrust the update to the button in the sub orm. The sa*e process or the modi ied main orm is then carried out automatically. The button can simply be labeled OE. The action assigned to it in the general properties o the button is 2efresh 'orm.

'igure ,: ;ain form as a filter for a subform The main orm consists only o the heading and the list bo6P the sub orm contains another heading) the table control rom the pre*ious *ersion and the button. The orm now unctions better in that'

T T

"o reader can now be edited) altered or deleted) and 1eaders can be ound more @uic,ly by typing into the control than by using a ilter.

5or a greater degree o unctionality &returns without alteration o pre*ious data( a second sub orm must be created) lin,ed to the same %oans table. To ensure the unctionality o the list bo6 in 5igure 3>) both sub orms must be placed one le*el urther down) as sub orms o a sub orm. 2ata is updated hierarchically rom the main orm down through the sub orms. The button in the pre*iously described orm must now be placed in the irst sub orm and not in the two sub orms that come under it.

/ere the 5orm "a*igator is used to show the di erent le*els. ?n the main orm we ha*e the te6t ield or the orm title and the list bo6 or inding the reader. The list bo6 appears at the bottom o the orm) as it is declared a ter the sub orm. #n ortunately this display se@uence cannot be altered. The sub orm has only one button) or updating its contents and at the same time sa*ing the main

3hapter ! 'orms

(7,

orm. :ne le*el urther down are the two additional sub orms. These are gi*en di erent names when created so that no con usion arises in any le*el o the tree.
9asically the names o orms and controls are without signi icance. /owe*er i these names are to be accessed by macros) they must be distinguishable. You cannot distinguish identical names at the same le*el. "aturally it ma,es sense) when creating larger orm structures to ha*e meaning ul names or orms and their controls. :therwise inding the right ield could @uic,ly become problematic.

9ote

The main orm and the sub orm use the same table. ?n the sub orm) no data are entered. That is why all the ields or this orm are set to ?o. The main orm and the sub orm are lin,ed through the ield) whose *alue is to be transmitted to the subGsub orms' the ?nteger ield in the 5ilter table.

?n the irst subGsub orm) no e6isting data are displayedP it is used only or creating new data. 5or this) the suggested ilter is ade@uate. :nly records matching the 2eader:.D and with an empty loan date ield &WLoan:DateJ .& ?+LL( will be displayed. ?n practice) this means an empty table control. +s the table control is not continuously updated) newly loaned media will remain within it until the OE update button is used either to select a new name or to trans er the data into the second subGsub orm.

((7

Base Handbook

The second subGsub orm re@uires more settings. This orm too contains data rom the W%oansW table. /ere the data is iltered or an empty return date. &W2eturn:DateJ .& ?+LL(. The data are sorted as in the pre*ious orm) so that the media on loan or the longest time are immediately *isible. The ollowing points are also important. :ld records can be changed) but no new records can be added. 2eletion is also impossible. This is the irst necessary step to pre*ent loan records rom being simply deleted later on. 9ut it would still be possible to change the medium and the loan date. There ore the properties o the columns will re@uire adRustment. F*entually the medium and the loan date should be displayed but protected rom modi ication. The table control is simply duplicated a ter the creation o the orm. This is done by selecting it) copying) deselecting) and then pasting it in rom the clipboard. The copy will be at the same position as the original) and will there ore need to be dragged away. + ter that) both table controls can be edited separately. The table control or the media return can be le t practically the same. :nly the write access or the ;edia and Loan date columns need to be changed. 7hile or the %oan date it is only necessary to choose 2ead onl0) this is not su icient or list bo6es. This setting does not pre*ent the list bo6 rom being used to ma,e changes. /owe*er i <nabled is set to ?o) a choice cannot be made there. + list bo6 contained within the table control is then displayed as a readGonly te6t ield. ?n the abo*e table control) all ields that ha*e nothing to do with the loan are remo*ed. :nly the medium as a selection ield and the loan date Loan:Date remain. ? inally the @uery or the list bo6 in the upper table control is selected) only those media are displayed which can actually be loaned out. 4ore about this is in Chapter B) Dueries.

3hapter ! 'orms

(((

'igure !7: *he selection field in the upper subform shows onl0 media that are not on loan. The media loan orm is already signi icantly more use ul. 7hen a reader arri*es at the loan counter) his or her name is searched. The media to be loaned can be selected using the list bo6 and the loan date entered. The *ab ,ey then ta,es you to the ne6t record.

((8

Base Handbook

+ inal impro*ement is also desirable' at present the loan date must be selected each time. ?magine a day in the library with perhaps 200 loan transactions) perhaps Rust one person) who has to loan out about 10 media each time. That would re@uire the same entry or the date ield o*er and o*er again. There must be a way to simpli y this. :ur main orm is lin,ed to the 5ilter table. The main orm wor,s only with the record that has as its primary ,ey the W?2W 0. 9ut additional ields can be built into the 5ilter table. +t present there is no ield that can store a date) but we can easily create a new ield with the ield name 2ate and the ield type Date. ?n the 5ilter table we now ha*e stored not only the 2eader:.D &W5ilterW.W?ntegerW( but also the Loan:Date &W5ilterW.W2ateW(.

?n the main orm) an additional date ield appears) along with a label re erring to its content. The *alue rom the date ield is stored in the 5ilter table and trans erred by the lin,ages rom sub orm to subGsub orm.

The lin,age between the two orms now re ers to two ields. The .nteger ield is bound to the 2eader:.D ield o the subGsub orm. The Date ield is bound to the Loan:Date ield. This ensures that the Loan:Date is automatically trans erred rom the 5ilter table to the %oans table when the loan is made.

'igure !(: *he date of the loan is entered onl0 once. Dhen the 2eader changesI it must be reentered. The date ield is now remo*ed rom the table control) so that the latter contains only one search ield. This would be the ideal re@uirement or speeding up e*en more the wor, o the library. 5or in act each medium will ha*e a printed accession number) so why does that ha*e to be searched;
3hapter ! 'orms ((

You can Rust enter the number directly. :r) better still) it could be scanned in with a barcode reader. Then media can be loaned as rapidly as the borrower can stow them in his bag. This is illustrated in the e6ample database. The abo*e e6ample should su ice or understanding the initial orm design but) as the e6ample database) 4ediaLwithoutL4acros.odb) de*elops the orm urther) the e6tra re inements are brie ly presented below.

The %oan orm shows the ollowing properties'

T T T T T T

1eaders are displayed in a table control. /ere you can also enter new readers. #sing a ilter) lin,ed to the 5ilter table) names can be iltered using their initial letter. .o) i you enter +) only people whose surname begins with + will be displayed. This iltering is caseGindependent. The subtitle shows again the name o the person to whom the loan is to be made. ? a loc, has been placed on this borrower) this is also displayed. The loan date is set to the current date. This is done in the ilter table using .D% such that) when no date is entered) the de ault *alue to be stored is the current date. %oanable media are selected using a list bo6. 7hen the #pdate button is pressed) the loan is trans erred to the table control below. The table control in the middle ser*es only to display the actual date o loan or the media. /ere it is also possible to correct an error retrospecti*ely by deleting the line.
Base Handbook

((!

T T T

?n the lower table control) as in the abo*e e6ample) alteration o media and loan dates is not possible. "or is it possible to delete records. +part rom the entry o the return date or) i appropriate) an e6tension o the loan) this table also displays the number o days or which the medium can be loaned and how many days remain o the current loan period. ? this remaining time becomes negati*e) the medium must be returned immediately. The issue is then loc,ed. ?t becomes possible again only when the medium is returned. + ter the return) the #pdate button need only be pressed once.

This orm) made by using @ueries) is signi icantly more comple6 in its structure than the pre*iously shown *ersion. You can learn more about the essentials o this in Chapter B) Dueries.

4ne view > many forms


7hile the e6ample or the %oans orm only in*ol*es entries into one table &the %oans table( and additionally allows entry into the simpler orm or new readers) the entry procedure or media is signi icantly more e6tensi*e. ?n its inal orm) the media table is surrounded by a total o eight additional tables &see Chapter 3) Tables(. The .ubtitle and relL4ediaLauthor tables are lin,ed to sub orms o the 4edia orm through a n'1 relationship. 9y contrast) tables with a 1'n relationship to the 4edia table should be represented by orms that lie abo*e the 4edia table. +s there are se*eral such tables) their *alues are entered into the main orm using list bo6es. The table o a main orm stands to the table o a sub orm in a 1'n relationship) or in some e6ceptional cases 1'1. There ore) a ter long use o the database) the main orm usually manages a table which has signi icantly ewer records in it than the table belonging to the sub orm. 4ultiple main orms cannot include the same sub orm. There ore it is not possible to create a orm arrangement or many simultaneous 1'n relationships in which the sub orm has the same content. 7hen there is a 1'n relationship or the table belonging to a orm) you can use a list bo6. /ere there are only a ew terms a*ailable rom another table) those whose oreign ,eys can be entered into the main orm=s table in this way.

%ist ield
1 n 1 n

%ist ield
1 n

%ist ield
1 n 1 n

4ain orm

.ub orm

.ub orm

#sing list bo6es) the main orm based on the 4edia table can be assigned *alues rom the Category) Town or $ublisher tables. .ub orms are used to lin, the relL4ediaL+uthor and .ubtitle tables with the main orm and through it with the 4edia table. The sub orm or the relL4ediaL+uthor table again consists o two list bo6es so that the oreign ,eys rom the +uthors and +uthorL+ddL?2 &additions might be or e6ample editor) photographer) and so on( do not ha*e to be entered directly as numbers. 5or the media entry orm) the list bo6es usually ha*e to be illed up gradually during the entry process. 5or this purpose) urther orms are built in alongside the main orm. They e6ist independently o the main orm.

3hapter ! 'orms

(("

Desktop

5orm 1
Control ield 1 Control ield 2 Control ield ...

5orm 2
Control ield 1 Control ield 2 Control ield ...

The o*erall orm or entering media loo,s li,e this'

:n the le t side is the main orm with a *iew to searching and entry o new media. :n the right side o the orm is a group bo6 with the label <dit list bo1 contents) pro*iding a separate area intended or illing up the list bo6es in the main orm. ? the database has not e6isted or long) it will o ten be necessary to ma,e entries into these ields. /owe*er) the more entries that are a*ailable or the list bo6es o the main orm) the less o ten will access to the table controls in the group bo6 be necessary.

((#

Base Handbook

The ollowing table controls are all subordinated as indi*idual side orms to the main orm) the entry orm.

/ere in each case the complete data or a table are entered. ?n the early stages) it is o ten necessary to ha*e recourse to these side orms) since not many authors are yet stored in the corresponding table. 7hen a new record is stored in one o the table controls) it is necessary to ind the corresponding list bo6 in the main orm and use the #pdate control &see "a*igation bar( to read in the new *alues. The 5orm "a*igator shows a correspondingly large list o orms.

3hapter ! 'orms

((9

The orms ha*e been indi*idually named to aid recognition. :nly the main orm still has the name o ;ain'orm gi*en to it by the 7i0ard. +ltogether there are eight parallel orms. The 'ilter orm hosts a search unction while the ;ain'orm orm is the main input inter ace. +ll the other orms relate to one or other o the table controls shown abo*e. 7ithout the table controls) the main orm loo,s somewhat simpler.

The ield or the search term lies in the 'ilter orm) the two table controls & or the author and the subtitle( lie in the subform o the 4edia Fntry main orm. ?n the 5orm "a*igator) this orm loo,s much more comple6) as all the controls and labels appear there. ?n the pre*ious orm) most o the ields were actually columns within the table controls and were thus in*isible to the 5orm "a*igator. #n ortunately the se@uence within the 5orm "a*igator cannot easily be changed. .o) or e6ample) it would seem more sensible to place the sub orms &ubtitle and >uthor as branches o ;ain'orm right at the beginning. 9ut within the 5orm "a*igator) indi*idual controls and sub orms are simply shown in the order in which they were created.

(()

Base Handbook

The 5orm 7i0ard pro*ides the controls with particular abbre*iations which appear ne6t to the icons and indicate what type o control this is. %abels begin with =lbl=) te6t ields with =t6t= and so on. +ltogether labels pro*ide only secondary in ormation or data entry. They can also be placed directly abo*e te6t rames and then do not appear in the 5orm "a*igator. The se@uence o the elements in the na*igator has nothing to do with the tab se@uence. That is determined by the >ctivation Order.

The acti*ation se@uence or a particular orm is in*o,ed) when an element o the orm is selected and then the >ctivation se@uence button is clic,ed. 5or a simple orm) it is not necessary to do things in this order) but where there are many parallel orms) the unction needs to ,now which

3hapter ! 'orms

((,

orm is intended. :therwise) by de ault) it is the irst orm in the 5orm "a*igator. ?n the abo*e e6ample) this contains only a single te6t ield.

The acti*ation se@uence allows all the elements that transmit data to the underlying table o the orm or can carry out actions) to be put in order. This corresponds to setting the acti*ation se@uence in the control properties listed on page E0. "ote that in the acti*ation se@uence) some controls appear or which the tab stop is actually switched o . They are included in the list) but are not in act accessed through the ,eyboard when wor,ing with the orm. 5ields can be automatically sorted in the order in which they appear on the orm bac,ground. The higher up a ield lies) the earlier it comes in the se@uence when you use +utomatic .ort. 5or ields at the same height) the le tmost ield comes irst. This sorting unctions without error only when the elements were e6actly positioned using the grid when the orm was created. :therwise you will need to adRust them. .imply select a control and use ;ove +p or ;ove Down to mo*e it higher or lower in the se@uence. ? there is a sub orm) >utomatic &ort Rumps directly into the sub orm a ter completing the main orm. ?n the case o a table control) this causes the cursor during ,eyboard input to be trapped within this sub ormP you can only ree it by using the mouse or by pressing 3trl4*ab. The >utomatic &ort unctions only once or a table control. + subse@uent sub orm with a table control will not be included. $arallel orms are not ta,en into account either. +n >utomatic &ort cannot be made retrospecti*ely or a sub orm with a table control. The sub orm must be completely remo*ed &temporarily mo*ed to another orm(.

The data substrate or the orm or media entry is in this case not a table but a @uery. This is necessary as the orm is to be used not Rust or entering records but also or searching. The orm also contains a te6t ield which shows) a ter sa*ing) whether the ?.9" number entered was correct. This too is only possible using a comprehensi*e @uery. To understand the bac,ground o this) it is there ore necessary to discuss the undamentals o @ueries) co*ered in Chapter B.
(87 Base Handbook

3hapter " Aueries

6eneral information on ;ueries


Dueries to a database are the most power ul tool that we ha*e to use databases in a practical way. They can bring together data rom di erent tables) calculate results where necessary) and @uic,ly ilter a speci ic record rom a mass o data. The large ?nternet databases that people use e*ery day e6ist mainly to deli*er a @uic, and practical result or the user rom a huge amount o in ormation by thought ul selection o ,eywords A including the searchGrelated ad*ertisements that encourage people to ma,e purchases.

Bntering ;ueries
Dueries can be entered both in the !#? and directly as .D% code. ?n both cases a window opens) where you can create a @uery and also correct it i necessary.

Creating ;ueries using the (uery #esign dialog


The creation o @ueries using the 7i0ard is brie ly described in Chapter < o the %etting &tarted guide) !etting .tarted with 9ase. /ere we shall e6plain the direct creation o @ueries in 2esign View. ?n the main database window) clic, the Dueries icon in the 2atabases section) then in the Tas,s section) clic, 3reate Auer0 in Design Biew. Two dialogs appear. :ne pro*ides the basis or a designG*iew creation o the @ueryP the other ser*es to add tables) *iews) or @ueries to the current @uery. +s our simple orm re ers to the %oan table) we will irst e6plain the creation o a @uery using this table.

5rom the tables a*ailable) select the %oan table. This window allows multiple tables &and also *iews and @ueries( to be combined. To select a table) clic, its name and then clic, the Add button. :r) doubleGclic, the tableKs name. Fither method adds the table to the graphical area o the Duery 2esign dialog. 7hen all necessary tables ha*e been selected) clic, the Close button. +dditional tables and @ueries can be added later i re@uired. /owe*er no @uery can be created without at least one table) so a selection must be made at the beginning.

(88

Base Handbook

'igure !8: >reas of the Auer0 Design dialog 5igure 42 shows the basic di*isions o the Duery 2esign dialog' the graphical area displays the tables that are to be lin,ed to the @uery. Their relationships to each other in relation to the @uery may also be shown. The table area is or the selection o ields or display) or or setting conditions related to these ields. Clic, on the ield in the irst column in the table area to re*eal a down arrow. Clic, this arrow to open the dropGdown list o a*ailable ields. The ormat is T)0&e_()*eH"%e&'_()*e A which is why all ield names here begin with the word Loan.

The selected ield designation L-)(HI has a special meaning. /ere one clic, allows you to add all ields rom the underlying table to the @uery. 7hen you use this ield designation with the wildcard K or all ields) the @uery becomes indistinguishable rom the table.
3hapter " Aueries (8

The irst i*e ields o the %oan table are selected. Dueries in 2esign 4ode can always be run as tests. This causes a tabular *iew o the data to appear abo*e the graphical *iew o the %oan table with its list o ields. + test run o a @uery is always use ul be ore sa*ing it) to clari y or the user whether the @uery actually achie*es its goal. : ten a logical error pre*ents a @uery rom retrie*ing any data at all. ?n other cases it can happen that precisely those records are displayed that you wished to e6clude. ?n principle a @uery that produces an error message in the underlying database cannot be sa*ed until the error is corrected.

(8!

Base Handbook

'igure ! : >n editable @uer0

'igure !!: > non-editable @uer0

?n the abo*e test) special attention should be paid to the irst column o the @uery result. The acti*e record mar,er &green arrow( always appears on the le t side o the table) here pointing to the irst record as the acti*e record. 7hile the irst ield o the irst record in 5igure 43 is highlighted) the corresponding ield in 5igure 44 shows only a dashed border. The highlight indicates that this ield can be modi ied. The records) in other words) are editable. The dashed border indicates that this ield cannot be modi ied. 5igure 43 also contains an e6tra line or the entry o a new record) with the ?2 ield already mar,ed as L>uto'ield-. This also shows that new entries are possible.

$ip

+ basic rule is that no new entries are possible i the primary ,ey in the @ueried table is not included in the @uery.

The %oanL2ate and 1eturnL2ate ields are gi*en aliases. This does not cause them to be renamed but only to appear under these names or the user o the @uery.

The table *iew abo*e shows how the aliases replace the actual ield names.

The 1eturnL2ate ield is gi*en not Rust an alias but also a search criterion) which will cause only those records to be displayed or which the 1eturnL2ate ield is empty. &Fnter .& <;$*H in the Criterion row o the 1eturnL2ate ield.( This e6clusion criterion will cause only those records to be displayed that relate to media that ha*e not yet been returned rom loan.

3hapter " Aueries

(8"

To learn the .D% language better) it is worth switching rom time to time between 2esign 4ode and .D% 4ode.

/ere the .D% ormula created by our pre*ious choices is re*ealed. To ma,e it easier to read) some line brea,s ha*e been included. #n ortunately the editor does not store these line brea,s) so when the @uery is called up again) it will appear as a single continuous line brea,ing at the window edge. &<L<3* begins the selection criteria. >& speci ies the ield aliases to be used. '2O; shows the table which is to be used as the source o the @uery. DH<2< gi*es the conditions or the @uery) namely that the 1eturnLdate ield is to be empty &.& ?+LL(. O2D<2 BH de ines the sort criteria) namely ascending order &+.C A ascending( or the two ields 1eaderL?2 and %oan date. This sort speci ication illustrates how the alias or the %oanL2ate ield can be used within the @uery itsel .
7hen wor,ing in 2esign View 4ode) use .& <;$*H to re@uire a ield be empty. 7hen wor,ing in .D% 4ode) use .& ?+LL which is what .D% &.tructured Duery %anguage( re@uires. 7hen you want to sort by descending order using .D%) use D<&3 instead o >&3.

$ip

.o ar the 4ediaL?2 and 1eaderL?2 ields are only *isible as numeric ields. The readersK names are unclear. To show these in a @uery) the 1eader table must be included. 5or this purpose we return to 2esign 4ode. Then a new table can be added to the 2esign *iew.

(8#

Base Handbook

/ere urther tables or @ueries can subse@uently be added and made *isible in the graphical user inter ace. ? lin,s between the tables were declared at the time o their creation &see Chapter 3) Tables() then these tables are shown with the corresponding direct lin,s.

? a lin, is absent) it can be created at this point by dragging the mouse rom W%oanW.W1eaderL?2W to W1eaderW.W?2W. "ow ields rom the 1eader table can be entered into the tabular area. The ields are initially added to the end o the @uery.

The position o the ields can be corrected in the tabular area o the editor using the mouse. .o or e6ample) the 5irstLname ield has been dragged into position directly be ore the %oanLdate ield.

"ow the names are *isible. The 1eaderL?2 has become super luous. +lso sorting by .urname and 5irstLname ma,es more sense than sorting by 1eaderL?2. This @uery is no longer suitable or use as a @uery that allows new entries into the resulting table) since it lac,s the primary ,ey or the added 1eader table. :nly i this primary ,ey is built in) does the @uery become editable again. ?n act it then becomes completely editable so that the readersK names can also be altered. 5or this reason) ma,ing @uery results editable is a acility that should be used with e6treme caution) i necessary under the control o a orm.
/a*ing a @uery that you can edit can create problems. Fditing data in the @uery also edits data in the underlying table and the records contained in the table. The data may not ha*e the same meaning. 5or e6ample) change the name o the reader) and you ha*e also changed what boo,s the reader has borrowed and returned. ? you ha*e to edit data) do so in a orm so you can see the e ects o editing data.

Caution

3hapter " Aueries

(89

F*en when a @uery can be urther edited) it is not so easy to use as a orm with list bo6es) which show the readersK names but contain the 1eaderL?2 rom the table. %ist bo6es cannot be added to a @ueryP they are only usable in orms.

? we now switch bac, to .D% View) we see that all ields are now shown in double @uotes' "T)0&e _()*e"H""%e&'_()*e". This is necessary so that the database ,nows rom which table the pre*iously selected ields come rom. + ter all) ields in di erent tables can easily ha*e the same ield names. ?n the abo*e table structure this is particularly true o the ?2 ield.
The ollowing @uery wor,s without putting table names in ront o the ield names' ')'&( "+,"" "-umber"" ".rice" FROM " tocK"" ",ispatch" @1'R' ",ispatch"."stocK+," E " tocK"."+,"

9ote

/ere the ?2 is ta,en rom the table which comes irst in the 51:4 de inition. The table de inition in the 7/F1F 5ormula is also super luous) because stoc,?2 only occurs once &in the 2ispatch table( and ?2 was clearly ta,en rom the .toc, table & rom the position o the table in the @uery(.

? a ield in the @uery has an alias) it can be re erred to A or e6ample in sorting A by this alias without a table name being gi*en. .orting is carried out in the graphical user inter ace according to the se@uence o ields in the tabular *iew. ? instead you want to sort irst by W%oan dateW and then by W%oanW.W1eaderL?2W) that can be done i '

T T

The se@uence o ields in the table area o the graphical user inter ace is changed &drag and drop W%oan dateW to the le t o W%oanW.W1eaderL?2W) or +n additional ield is added) set to be in*isible) Rust or sorting &howe*er) the editor will register this only temporarily i no alias was de ined or it( _add another W%oan dateW ield Rust be ore W%oanW.W1eaderL?2W or add another W%oanW.W1eaderL?2W ield Rust a ter W%oan dateW`) or The te6t or the :12F1 9Y command in the .D% editor is altered correspondingly &:12F1 9Y W%oan dateW) W%oanW.W1eaderL?2W(.

.peci ying the sort order ma0 not be completel0 error-free) depending on the %ibre: ice *ersion. 5rom *ersion 3.B.3) sorting rom the .D% *iew is correctly registered and displayed in the graphical user inter ace) including the ields that are used in the @uery but are not *isible in the @uery output. &These ields do not ha*e a chec, in the Visible row.(
+ @uery may re@uire a ield that is not part o the @uery output. ?n the graphic in the ne6t section) 1eturnL2ate is an e6ample. This @uery is searching or records that do not contain a return date. This ield pro*ides a criterion or the @uery but no use ul *isible data.

$ip

!sin# functions in a query


The use o unctions allows a @uery to pro*ide more than Rust a iltered *iew o the data in one or more tables. The ollowing @uery calculates how many media ha*e been loaned out) depending on the 1eaderL?2.

(8)

Base Handbook

5or the ?2 o the %oan table) the 3ount unction is selected. ?n principle it ma,es no di erence which ield o a table is chosen or this. The only condition is' *he field must not be empt0 in an0 of the records. 5or this reason) the primary ,ey ield) which is ne*er empty) is the most suitable choice. +ll ields with a content other than "#%% are counted. 5or the 1eaderL?2) which gi*es access to reader in ormation) the %rouping unction is chosen. ?n this way) the records with the same 1eaderL?2 are grouped together. The result shows the number o records or each 1eaderL?2. +s a search criterion) the 1eturnL2ate is set to I?. F4$TYJ) as in the pre*ious e6ample. &9elow) the .D% or this is DH<2< M2eturn:DateN .& ?+LL.(

The result o the @uery shows that 1eaderL?2 =0= has a total o 3 media on loan. ? the 3ount unction had been assigned to the 1eturnL2ate instead o the ?2) e*ery 1eaderL?2 would ha*e =0= media on loan) since 1eturnLdate is prede ined as "#%%. The corresponding 5ormula in .D% code is shown abo*e. +ltogether the graphical user inter ace pro*ides the ollowing unctions) which correspond to unctions in the underlying /.D%29. 5or an e6planation o the unctions) see IDuery enhancement using .D% 4odeI on page 134.

3hapter " Aueries

(8,

? one ield in a @uery is associated with a unction) all the remaining ields mentioned in the @uery must also be associated with unctions i they are to be displayed. ? this is not ensured) you get the ollowing error message'

+ somewhat ree translation would be' The ollowing e6pression contains no aggregate unction or grouping.
7hen using 2esign View 4ode) a ield is only *isible i the Bisible row contains a chec, mar, or the ield. 7hen using .D% 4ode) a ield is only *isible when it ollows the ,eyword) .F%FCT.

$ip

9ote

7hen a ield is not associated with a unction) the number o rows in the @uery output is determined by the search conditions. 7hen a ield is associated with a unction) the number o rows in the @uery output is determined by whether there is any grouping or not. ? there is no grouping) there is only one row in the @uery output. ? there is grouping) the number o rows matches the number o distinct *alues that the grouping ield has. .o) all o the *isible ields must either be associated with a unction or not be associated with a function to pre*ent this con lict in the @uery output. + ter this) the complete @uery is listed in the error message) but un ortunately without the o ending ield being named speci ically. ?n this case the ield 1eturnL2ate has been added as a displayed ield. This ield has no unction associated with it and is not included in the grouping statement either. The in ormation pro*ided by using the 4ore button is not *ery illuminating or the normal database user. ?t Rust displays the .D% error code.

To correct the error) remo*e the chec, mar, in the Visible row or the 1eturnL2ate ield. ?ts search condition &Criterion( is applied when the @uery is run) but it is not *isible in the @uery output. #sing the !#?) basic calculations and additional unctions can be used.

( 7

Base Handbook

.uppose that a library does not issue recall notices when an item is due or return) but issues o*erdue notices in cases where the loan period has e6pired and the item has not been returned. This is common practice in school and public libraries that issue loans only or short) i6ed periods. ?n this case the issue o an o*erdue notice automatically means that a ine must be paid. /ow do we calculate these ines; ?n the @uery shown abo*e) the %oan and 1ecalls tables are @ueried Rointly. 5rom the count o the data entries in the table 1ecalls) the total number o recall notices is determined. The ine or o*erdue media is set in the @uery to 2.00 b. ?nstead o a ield name) the ield designation is gi*en as C-=(t(Re7)&&sHD)te)I8. The graphical user inter ace adds the @uotation mar,s and con*erts the term IcountJ into the appropriate .D% command.
4nly for people who use a comma for their decimal separatorG

Caution

? you wish to enter numbers with decimal places using the graphical user inter ace) you must ensure that a decimal point rather than a comma is used to separate the decimal places within the inal .D% statement. Commas are used as ield separators) so new @uery ields are created or the decimal part. +n entry with a comma in the .D% *iew always leads to a urther ield containing the numerical *alue o the decimal part.

The @uery now yields or each medium still on loan the ines that ha*e accrued) based on the recall notices issued and the additional multiplication ield. The ollowing @uery structure will also be use ul or calculating the ines due rom indi*idual users.

The W%oanW.W?2W and W%oanW.W4ediaL?2W ields ha*e been remo*ed. They were used in the pre*ious @uery to create by grouping a separate record or each medium. "ow we will be grouping only by the reader. The result o the @uery loo,s li,e this'

3hapter " Aueries

( (

?nstead o listing the media or 1eaderL?2 Y 0 separately) all the W1ecallsW.W2ateW ields ha*e been counted and the total o <.00b entered as the ine due.

/elationshi definition in the query


7hen data is searched or in tables or orms) the search is usually limited to one table or one orm. F*en the path rom a main orm to a sub orm is not na*igable by the builtGin search unction. 5or such purposes) the data to be searched or are better collected by using a @uery.

The simple @uery or the Title ield rom the 4edia table shows the test entries or this table) > records in all. 9ut i you enter .ubtitle into the @uery table) the record content o the 4edia table is reduced to only 2 Titles. :nly or these two Titles are there also .ubtitles in the table. 5or all the other Titles) no subtitles e6ist. This corresponds to the Roin condition that only those records or which the 4ediaL?2 ield in the .ubtitle table is e@ual to the ?2 ield in the 4edia table should be shown. +ll other records are e6cluded.

( 8

Base Handbook

The Roin conditions must be opened or editing to display all the desired records. 7e re er here not to Roins between tables in 2elationship design but to Roins within @ueries.

9y de ault) relationships are set as .nner Ooins. The window pro*ides in ormation on the way this type o Roin wor,s in practice. The two pre*iously selected tables are listed as Tables ?n*ol*ed. They are not selectable here. The rele*ant ields rom the two tables are read rom the table de initions. ? there is no relationship speci ied in the table de inition) one can be created at this point or the @uery. /owe*er) i you ha*e planned your database in an orderly manner using /.D%29) there should be no need to alter these ields. The most important setting is the Ooin option. /ere relationships can be so chosen that all records rom the .ubtitle table are selected) but only those records rom 4edia which ha*e a subtitle entered in the .ubtitle table. :r you can choose the opposite' that in any case all records rom the table 4edia are displayed) regardless o whether they ha*e a subtitle. The ?atural option speci ies that the lin,ed ields in the tables are treated as e@ual. You can also a*oid ha*ing to use this setting by de ining your relationships properly at the *ery start o planning your database. 5or the type 2ight Poin) the description shows that all records rom the 4edia table will be displayed &.ubtitle 1?!/T -:?" 4edia(. +s there is no .ubtitle that lac,s a title in 4edia but there are certainly Titles in 4edia that lac, a .ubtitle) this is the right choice.

3hapter " Aueries

+ ter con irming the right Poin the @uery results loo, as we wanted them. Title and .ubtitle are displayed together in one @uery. "aturally Titles appear more than once as with the pre*ious relationship. /owe*er as long as hits are not being counted) this @uery can be used urther as a basis or a search unction. .ee the code ragments in this chapter) in Chapter > &4acros() and in Chapter < &2atabase Tas,s(.

(uery enhancement using ?(+ -ode


? during graphical entry you use 8iew 5 ?witch #esign 8iew 4nO4ff to switch design *iew o ) you see the .D% command or what pre*iously appeared in 2esign View. This is the best way or beginners to learn the .tandard Duery %anguage or 2atabases. .ometimes it is also the only way
( ! Base Handbook

to enter a @uery into the database when the !#? cannot translate your re@uirements into the necessary .D% commands. ')'&( I FROM "(able_%ame" This will show e*erything that is in the TableLname table. The WHW represents all the ields o the table. ')'&( I FROM "(able_%ame" @1'R' "Field_%ame" E G#arlG /ere there is a signi icant restriction. :nly those records are displayed or which the ield 5ieldLname contains the term =Qarl= A the e6act term) not or e6ample =Qarl Fgon=. .ometimes @ueries in 9ase cannot be carried out using the !#?) as particular commands may not be recogni0ed. ?n such cases it is necessary to switch 2esign View o and use Bdit 5 )un ?(+ command directly or direct access to the database. This method has the disad*antage that you can only wor, with the @uery in .D% 4ode.

2irect use o .D% commands is also accessible using the graphical user inter ace) as the abo*e igure shows. Clic, the icon highlighted &2un &AL command directl0( to turn the 2esign View : /:n icon o . "ow when you clic, the 2un icon) the @uery runs the .D% commands directly. /ere is an e6ample o the e6tensi*e possibilities a*ailable or posing @uestions to the database and speci ying the type o result re@uired' ')'&( 6>)+M+( ;o<<set= ;limit= 7 (O. ;limit=?96A)) 7 ,+ (+-&(9 > ; electFFormulatio%= 7 "(able_%ame".I 7 I ? 6" ...9 6+-(O 6&A&1', 7 ('M. 7 (':(9 "%ew_(able"9 FROM "(able_list" 6@1'R' B)F'xpressio%9 68ROA. !/ B)F'xpressio% 6" ...99 61A0+-8 B)F'xpressio%9 6> A-+O- 6A)) 7 ,+ (+-&(9 7 >M+-A 6,+ (+-&(9 7 ':&'.( 6,+ (+-&(9 ? 7 +-('R '&( 6,+ (+-&(9 ? Buery stateme%t9 6OR,'R !/ OrderF'xpressio% 6" ...99 6)+M+( ;limit= 6OFF '( ;o<<set=995 AI+I-I$ Hoffset5 Hlimit5 D $4P Hlimit5JEG This limits the number o records to be displayed. LIMIT E0 80 starts at the 11th record and shows the ollowing 20 records. TOP E0 always shows the irst 10 records. This is the same as LIMIT 0 E0. LIMIT E0 0 omits the irst 10 records and displays all records starting rom the 11th. You can do the same thing by using the last .F%FCT condition in the ormula 2LIMIT ,&%*%t1 2O"" ET ,-CCset166. LIMIT E0 shows only 10 records. +dding O"" ET 80 causes the display to begin at the 21st record. 9e ore you use this inal orm o display limitation) you need to include a sorting condition &:12F1 9Y ](. %imiting the display o @uery results is only possible using direct .D% commands. 9y doing this) you determine how the @uery data is sorted and hence what data will be shown. AA++ D #I?$I9C$E ELECT ALL is the de ault. +ll records are displayed that ul ill the search conditions. F6ample' ELECT ALL "N)*e" "ROM "T)0&e_()*e" yields all namesP i W$eterW occurs three times and WFgonW our times in the table) these names are displayed three and our times respecti*ely. ELECT DI TINCT "N)*e" "ROM "T)0&e_()*e" suppresses @uery results
3hapter " Aueries ( "

that ha*e the same content. ?n this case) c$eterK and cFgonK occur only once. DI TINCT re ers to the whole o the record that is accessed by the @uery. .o i ) or e6ample) the surname is as,ed or as well) records or c$eter 4XllerK and c$eter 4aierK will count as distinct. F*en i you speci y the DI TINCT condition) both will be displayed. H?electQFormulation5 > 'xpressio% 7 &OA-(*I4 7 > &OA-( 7 M+- 7 MA: 7 AM 7 A08 7 OM' 7 '0'R/ 7 0AR_.O. 7 0AR_ AM. 7 (,,'0_.O. 7 (,,'0_ AM. ? *6A)) 7 ,+ (+-&(99 'xpressio%4 ? 66A 9 "display_%ame"9 5ield names) calculations) record totals are all possible entries. ?n addition di erent unctions are a*ailable or the ield shown. F6cept or COUNT(I) &which counts all the records( none o these unctions access NULL ields. &OA-( 7 M+- 7 MA: 7 AM 7 A08 7 OM' 7 '0'R/ 7 0AR_.O. 7 0AR_ AM. 7 (,,'0_.O. 7 (,,'0_ AM. COUNT("N)*e") counts all entries or the ield "ame. MIN("N)*e") shows the irst name alphabetically. The result o this unction is always ormatted Rust as it occurs in the ield. Te6t is shown as te6t) integers as integers) decimals as decimals and so on. MAX("N)*e") shows the last name alphabetically. UM("N=*0e/") can add only the *alues in numerical ields. The unction ails or date ields. AV+("N=*0e/") shows the a*erage o the contents o a column. This unction too is limited to numerical ields. OME(""%e&'_N)*e"), EVERY(""%e&'_N)*e")G 5ields used with these unctions must ha*e the Yes/"o _9::%F+"` ield type &contains only 0 or 1(. 5urthermore) they produce a summary o the ield content to which they are applied. OME returns *2+< &or (( i at least one entry or the ield is () and it returns '>L&< &or 7( only i all the entries are 7. EVERY returns ( only i e*ery entry or the ield is () and returns '>L&< i at least one entry is 7.
The 9oolean ield type is Yes/"o_9::%F+"`. /owe*er) this ield contains only 0 or 1. ?n @uery search conditions) use either *2+<) () '>L&< or 7. 5or the Hes condition) you can use either *2+< or (. 5or the ?o condition) use either '>L&< or 7. ? you try to use either IYesJ or I"oJ instead) you get an error message. Then you will ha*e to correct your error.

$ip

F6ample' ')'&( "&lass"" '0'R/*" wimmer"4 FROM "(ableC" 8ROA. !/ "&lass"5 3lass contains the names o the swimming class. &wimmer is a 9oolean ield describing whether a student can swim or not &1 or 0(. &tudents contains the names o the students. *able( contains these ields' its primary ,ey) Class) .wimmer) and .tudents. :nly Class and .wimmer are needed or this @uery. 9ecause the @uery is grouped by the entries o the ield Class) FVF1Y will return a *alue or the ield) .wimmer) or each class. 7hen e*ery person in a swimming class can swim) FVF1Y returns T1#F. :therwise FVF1Y returns 5+%.F because at least one student o the class can not swim. .ince the output or the .wimmer ield is a chec,bo6) + chec, mar, indicates T1#F) and no chec, mar, indicates 5+%.F. VAR_POP 4 VAR_ AMP 4 TDDEV_POP 4 TDDEV_ AMP are statistical unctions and a ect only integer and decimal ields. +ll these unctions return 0) i the *alues within the group are all e@ual.

( #

Base Handbook

The statistical unctions do not allow the DI TINCT limitation to be used. 9asically they calculate o*er all *alues co*ered by the @uery) whereas DI TINCT e6cludes records with the same *alues rom the display. 2A 6 "'%s<&)J_()*e"# The ields can be gi*en a di erent designation &alias( within the @uery. R$able@nameR.S D S A= ...E Fach ield to be displayed is gi*en with its ield names) separated by commas. ? ields rom se*eral tables are entered into the @uery) a combination o the ield name with the table name is necessary' "T)0&e_()*e"H""%e&'_()*e". ?nstead o a detailed list o all the ields o a table) its total content can be displayed. 5or this you use the symbol WHW. ?t is then unnecessary to use the table name) i the results will only apply to the one table. /owe*er) i the @uery includes all o the ields o one table and at least one ield rom a second table) use' "T)0&e_()*e E"HI, KT)0&e_()*e 8LHL"%e&'_()*eLH AI9$4 ACAC3B# D $B-P D $BF$E Rnew@tableRE The result o this @uery is to be written directly into a new table which is named here. The ield properties or the new table are de ined rom the ield de initions contained in the @uery. 7riting into a new table does not wor, rom .D% 4ode as this handles only displayable results. ?nstead you must use $ools 5 ?(+. The resultant table is initially not editable as it lac,s a primary ,ey. F)4- H$able@list5 "(able_%ame C" 6>&RO 7 +--'R 7 )'F( OA('R 7 R+81( OA('R? LO+"(able_%ame D" O- 'xpressio%9 6" ...9 The tables which are to be Rointly searched are usually in a list separated by commas. The relationship o the tables to one another is then additionally de ined by the ,eyword !HERE. ? the tables are bound through a MOIN rather than a comma) their relationship is de ined by the term beginning with ON which occurs directly a ter the second table. + simple MOIN has the e ect that only those records are displayed or which the conditions in both the tables apply. F6ample' .F%FCT WTable1W.W"ameW) WTable2W.WClassW 51:4 WTable1W) WTable2W 7/F1F WTable1W.WClass?2W Y WTable2W.W?2W is e@ui*alent to' ')'&( "(ableC"."-ame"" "(ableD"."&lass" FROM "(ableC" LO+- "(ableD" O- "(ableC"."&lass+," E "(ableD"."+," /ere the names and the corresponding classes are displayed. ? a name has no class listed or it) that name is not included in the display. ? a class has no names) it is also not displayed. The addition o INNER does not alter this. ')'&( "(ableC"."-ame"" "(ableD"."&lass" FROM "(ableC" )'F( LO+"(ableD" O- "(ableC"."&lass+," E "(ableD"."+," ? LE"T is added) all W"amesW rom WTable1W are displayed e*en i they ha*e no WClassW. ? ) on the contrary) RI+HT is added) all Classes are displayed e*en i they ha*e no names in them. +ddition o OUTER need not be shown here. &1ight :uter -oin is the same thing as 1ight -oinP %e t :uter -oin is the same thing as %e t -oin.(

3hapter " Aueries

( 9

')'&( "(ableC".".layerC"" "(ableD".".layerD" FROM "(ableC" A "(ableC" &RO LO+- "(ableD" A "(ableC" @1'R' "(ableC".".layerC" ;= "(ableD".".layerD" + CRO MOIN re@uires the table to be supplied with an alias) but the addition o the term ON is not always necessary. +ll records rom the irst table are paired with all records rom the second table. Thus the abo*e @uery yields all possible pairings o records rom the irst table with those o the second table e6cept or pairings between records or the same player. ?n the case o a CRO MOIN" the condition must not include a lin, between the tables speci ied in the ON term. ?nstead) !HERE conditions can be entered. ? the conditions are ormulated e6actly as in the case o a simple -:?") you get the same result' ')'&( "(ableC"."-ame"" "(ableD"."&lass" FROM "(ableC" LO+- "(ableD" O- "(ableC"."&lass+," E "(ableD"."+," gi*es the same result as ')'&( "(ableC"."-ame"" "(ableD"."&lass" FROM "(ableC" A "(ableC" &RO LO+- "(ableD" A "(ableD" @1'R' "(ableC"."&lass+," E "(ableD"."+," A03B)B ?(+QB/pressionE The standard introduction or conditions to re@uest a more accurate iltering o the data. /ere too the relationships between tables are usually de ined i they are not lin,ed together with -:?". A6)4:P C ?(+QB/pression A= TEE #se this when you want to di*ide the @uery data into groups be ore applying the unctions to each one o the groups separately. The di*ision is based upon the *alues o the ield or ields contained in the !1:#$ 9Y term. F6ample' ')'&( "-ame"" AM*"+%put"F"Output"4 A "!ala%ce" FROM "(ableC" 8ROA. !/ "-ame"5 1ecords with the same name are summed. ?n the @uery result) the sum o I(<=t D O=t<=t is gi*en or each person. This ield is to be called B)&)(7e. Fach row o the @uery result contains a *alue rom the I"ameJ table and the calculated balance or that speci ic *alue.
7hen ields are processed using a particular unction & or e6ample COUNT, UM ]() all ields that are not processed with a unction but should be displayed are grouped together using +ROUP BY.

$ip

A3A8I96 ?(+QB/pressionE The HAVIN+ ormula closely resembles the !HERE ormula. The di erence is that the 7/F1F ormula applies to the *alues o selected ields in the @uery. The /+V?"! ormula applies to selected calculated *alues. .peci ically) the 7/F1F ormula can not use an aggregate unction as part o a search conditionP the /+V?"! ormula does. The /+V?"! ormula ser*es two purposes as shown in the two e6amples below. ?n the irst one) the search condition re@uires that the minimum runGtime be less than 40 minutes. ?n the second e6ample) the search condition re@uires that an indi*idual=s balance must be positi*e. The @uery results or the irst one lists the names o people whose runGtime has been less than 40 minutes at least one time and the minimum runGtime. $eople whose runGtimes ha*e all be greater than 40 minutes are not listed. The @uery results or the second one lists the names o people who ha*e a total greater output than input and their balance. $eople whose balance is 0 or less are not listed.
( ) Base Handbook

F6amples' ')'&( "-ame"" "Ru%time" FROM "(ableC" 8ROA. !/ "-ame"" "Ru%time" 1A0+-8 M+-*"Ru%time"4 ; G33MN3M33G5 ')'&( "-ame"" AM*"+%put"F"Output"4 A "!ala%ce" FROM "(ableC" 8ROA. !/ "-ame" 1A0+-8 AM*"+%put"F"Output"4 = 35 A?(+ B/pressionE .D% e6pressions are combined according to the ollowing scheme' 6-O(9 co%ditio% 6> OR 7 A-, ? co%ditio%9 F6ample' ')'&( I FROM "(able_%ame" @1'R' -O( "Retur%_date" + -A)) A-, "Reader+," E D5 The records read rom the table are those or which a I1eturnLdateJ has been entered and the W1eader?2W is 2. ?n practice this means that all media loaned to a speci ic person and returned can be retrie*ed. The conditions are only lin,ed with AND. The NOT re ers only to the irst condition. ')'&( I FROM "(able_%ame" @1'R' -O( *"Retur%_date" + -A)) A-, "Reader+," E D45 $arentheses around the condition) with NOT outside them shows only those records that do not ul ill the condition in parentheses completely. This would co*er all records) e6cept or those or W1eader?2W number 2) which ha*e not yet been returned. A?(+ B/pressionEG conditions > value 677 value9 + *alue can be single or se*eral *alues Roined by two *ertical lines 44. "aturally this applies to ield contents as well. ')'&( " ur%ame" 77 G" G 77 "First_%ame" A "-ame" FROM "(able_%ame" The content o the ields W.urnameW and W5irstLnameW are displayed together in a ield called W"ameW. "ote that a comma and a space are inserted between W.urnameW and W5irstLnameW. 7 value > E 7 ; 7 ;E 7 = 7 =E 7 ;= 7 OE ? value These signs correspond to the wellG,nown mathematical operators' d F@ual to ^ %ess than ^ %ess than or e@ual to ^ !reater than ^ !reater than or e@ual to ^ "ot e@ual to ^ "ot e@ual to e 7 value + 6-O(9 -A)) The corresponding ield has no content) because nothing has been written to it. This cannot be determined unambiguously in the !#?) since a *isually empty te6t ield does not mean that the ield is completely without content. /owe*er the de ault setGup in 9ase is that empty ields in the database are set to NULL. 7 ':+ ( *Buery_result4 F6ample' ')'&( "-ame" FROM "(ableC" @1'R' ':+ ( * ')'&( "First_%ame" FROM "(ableD" @1'R' "(ableD"."First_%ame" E "(ableC"."-ame"4 The names rom Table1 are displayed or which irst names are gi*en in Table2. 7 0alue !'(@''- 0alue A-, 0alue BET!EEN :)&=eE AND :)&=e8 yields all *alues rom *alue1 up to and including *alue2. ? the *alues are letters) an alphabetic sort is used in which lowerGcase letters ha*e the same *alue as the corresponding upperGcase ones.
3hapter " Aueries ( ,

')'&( "-ame" FROM "(able_%ame" @1'R' "-ame" !'(@''- GAG A-, G'G5 This @uery yields all names beginning with +) 9) C or 2 &and also with the corresponding lowerG case letters(. +s F is set as the upper limit) names beginning with F are not included. The letter F itsel occurs Rust before the names that begin with F. 7 value 6-O(9 +- * >value 6" ...9 7 Buery result ? 4 This re@uires either a list o *alues or a @uery. The condition is ul illed i the *alue is included in the *alue list or the @uery result. 7 value 6-O(9 )+#' value 6' &A.'9 value ? The LIKE operator is one that is needed in many simple search unctions. The *alue is entered using the ollowing pattern' A?A stands or any number o characters &including 0() A_A replaces e6actly one character. To search or =?= or =_= itsel ) the characters must immediately ollow another character de ined as E CAPE. ')'&( "-ame" FROM "(able_%ame" @1'R' "-ame" )+#' GP_QG ' &A.' GPG This @uery displays all names that begin with an underscore. =@= is de ined here as the E CAPE character. A?(+ B/pressionEG values 6H 7 F9 > 'xpressio% 6> H 7 F 7 I 7 / 7 77 ? 'xpressio%9 The *alues may ha*e a preceding sign. +ddition) subtraction) multiplication) di*ision and concatenation o e6pressions are allowed. +n e6ample o concatenation' ')'&( " ur%ame"77G" G77"First_%ame" FROM "(able" ?n this way records are displayed by the @uery with a ield containing W.urname) 5irstLnameW. The concatenation operator can be @uali ied by the ollowing e6pressions. 7 * &o%ditio% 4 .ee the pre*ious section or this. 7 Fu%ctio% * 6.arameter9 6"...9 4 .ee the section on 5unctions in the appendi6. The ollowing @ueries are also re erred to as subG@ueries &subselects(. 7 Buery result which yields exactly o%e a%swer +s a record can only ha*e one *alue in each ield) only a @uery which yields precisely one *alue can be displayed in ull. 7 >A-/7A))? *Bueryresult which yields exactly o%e a%swer <rom a whole colum%4 : ten there is a condition that compares an e6pression with a whole group o *alues. Combined with ANY this signi ies that the e6pression must occur at least once in the group. This can also be speci ied using the IN condition. N ANY yields the same result as IN. Combined with ALL it signi ies that all *alues o the group must correspond to the one e6pression. A?(+ B/pressionEG B/pression > G(extG 7 +%te$er 7 Floati%$Fpoi%t %umber 7 6"(able".9"Field" 7 (RA' 7 FA) ' 7 -A)) ? 9asically *alues ser*e as arguments or *arious e6pressions) dependent on the source ormat. To search or the content o te6t ields) place the content in @uotes. ?ntegers are written without

(!7

Base Handbook

@uotes) as are loatingGpoint numbers. 5ields stand or the *alues that occur in those ields in the table. #sually ields are compared either with each other or with speci ic *alues. ?n .D%) ield names should be placed in double @uotes) as they may not be correctly recogni0ed otherwise. #sually .D% assumes that te6t without double @uotes is without special characters) that is a single word without spaces and in upper case. ? se*eral tables are contained in the @uery) the table name must be gi*en in addition to the ield name) separated rom the latter by a period. TRUE and "AL E usually deri*e rom Yes/"o ields. NULL means no content. ?t is not the same thing as 0 but rather corresponds to IemptyJ. :9I49 AA++ D #I?$I9C$E (uery@result This lin,s @ueries so that the content o the second @uery is written under the irst. 5or this to wor,) all ields in both @ueries must match in type. This lin,age o se*eral @ueries unctions only in direct .D% command mode. ')'&( "First_%ame" FROM "(ableC" A-+O- ,+ (+-&( ')'&( "First_%ame" FROM "(ableD"5 This @uery yields all irst names rom table1 and Table2P the additional term DI TINCT means that no duplicate irst names will be displayed. DI TINCT is the de ault in this conte6t. 9y de ault the irst names are sorted alphabetically in ascending order. ALL causes all irst names in Table1 to be displayed) ollowed by the irst name in Table2. ?n this case the de ault is to sort by primary ,ey. -I9:? A#I?$I9C$E D BFCBP$ A#I?$I9C$E (uery@result ')'&( "First_%ame" FROM "(ableC" ':&'.( ')'&( "First_%ame" FROM "(ableD"5 .hows all irst names rom table1 e6cept or the irst names contained in Table 2. MINU and EXCEPT lead to the same result. .orting is alphabetic. I9$B)?BC$ A#I?$I9C$E (uery@result ')'&( "First_%ame" FROM "(ableC" +-('R '&( ')'&( "First_%ame" FROM "(ableD"5 This displays the irst names that occur in both tables. .orting is again alphabetic. +t present this only wor,s in direct .D% command mode. A4)#B) C 4rderingQB/pression A= TEE The e6pression can be a ield name) a column number &beginning with 1 rom the le t() an alias & ormulated with A <or example( or a composite *alue e6pression &see _.D% F6pression`' *alues(. The sort order is usually ascending &A C(. ? you want a descending sort you must speci y DE C e6plicitly.
')'&( "First_%ame"" " ur%ame" A "-ame" FROM "(ableC" OR,'R !/ " ur%ame"5 "-ame" FROM "(ableC" OR,'R !/ D5 "-ame" FROM "(ableC" OR,'R !/ "-ame"5

is identical to
')'&( "First_%ame"" " ur%ame" A

is identical to
')'&( "First_%ame"" " ur%ame" A

:sing an alias in a ;uery


Dueries can reproduce ields with changed names. ')'&( "First_%ame"" " ur%ame" A "-ame" FROM "(ableC" The ield &urname is called ?ame in the display.

3hapter " Aueries

(!(

? a @uery in*ol*es two tables) each ield name must be preceded by the name o the table' ')'&( "(ableC"."First_%ame"" "(ableC"." ur%ame" A "-ame"" "(ableD"."&lass" FROM "(ableC"" "(ableD" @1'R' "(ableC"."&lass_+," E "(ableD"."+," The table name can also be gi*en an alias) but this will not be reproduced in table *iew. ? such an alias is set) all the table names in the @uery must be altered accordingly' ')'&( "a"."First_%ame"" "a"." ur%ame" A "-ame"" "b"."&lass" FROM "(ableC" A "a"" "(ableD" A "b" @1'R' "a"."&lass_+," E "b"."+," The assignment o an alias or a table can be carried out more brie ly without using the term +.' ')'&( "a"."First_%ame"" "a"." ur%ame" A "-ame"" "b"."&lass" FROM "(ableC" "a"" "(ableD" "b" @1'R' "a"."&lass_+," E "b"."+," This howe*er ma,es the code less readable. 9ecause o this) the abbre*iated orm should be used only in e6ceptional circumstances.

(ueries for the creation of list bo/ fields


%ist bo6 ields show a *alue that does not correspond to the content o the underlying table. They are used to display the *alue assigned by a user to a oreign ,ey rather than the ,ey itsel . The *alue that is inally sa*ed in the orm must not occur in the irst position o the list bo6 ield. ')'&( "First_%ame"" "+," FROM "(ableC"5 This @uery would show all irst names and the primary ,ey W?2W *alues that the ormKs underlying table pro*ides. : course it is not yet optimal. The irst names appear unsorted and) in the case o identical irst names) it is impossible to determine which person is intended. ')'&( "First_%ame"77G G77" ur%ame"" "+," FROM "(ableC" OR,'R !/ "First_%ame"77G G77" ur%ame"5 "ow the irst name and the surname both appear) separated by a space. The names become distinguishable and are also sorted. 9ut the sort ollows the usual logic o starting with the irst letter o the string) so it sorts by irst name and only then by surname. + di erent sort order to that in which the ields are displayed would only be con using. ')'&( " ur%ame"77G" G77"First_%ame"" "+," FROM "(ableC" OR,'R !/ " ur%ame"77G" G77"First_%ame"5 This now leads to a sorting that corresponds better to normal custom. 5amily members appear together) one under anotherP howe*er di erent amilies with the same surname would be interlea*ed. To distinguish them) we would need to group them di erently within the table. There is one inal problem' i two people ha*e the same surname and irst name) they will still not be distinguishable. :ne solution might be to use a name su i6. 9ut imagine how it would loo, i a salutation read 4r W4Xller ??WU ')'&( " ur%ame"77G" G77"First_%ame"77G F +,MG77"+,"" "+," FROM "(ableC" OR,'R !/ " ur%ame"77G" G77"First_%ame"77"+,"5 /ere all records are distinguishable. 7hat is actually displayed is W.urname) 5irst name A ?2'?2 *alueW. ?n the loan orm) there is a list bo6 which only shows the media that ha*e not yet been loaned out. ?t is created using the ollowing .D% ormula' ')'&( "(itle" 77 G F -r. G 77 "+,"" "+," FROM "Media" @1'R' "+," -O( +- * ')'&( "Media_+," FROM ")oa%" @1'R' "Retur%_,ate" + -A))4 OR,'R !/ "(itle" 77 G F -r. G 77 "+," A &

(!8

Base Handbook

(ueries as a basis for additional information in forms


? you wish a orm to display additional ?n ormation that would otherwise not be *isible) there are *arious @uery possibilities. The simplest is to retrie*e this in ormation with independent @ueries and insert the results into the orm. The disad*antage o this method is that changes in the records may a ect the @uery result) but un ortunately these changes are not automatically displayed. /ere is an e6ample rom the sphere o stoc, control or a simple chec,out. The chec,out table contains totals and oreign ,eys or stoc, items) and a receipt number. The shopper has *ery little in ormation i there is no additional @uery result printed on the receipt. + ter all) the items are identi ied only by reading in a barcode. 7ithout a @uery) the orm shows only' $otal
3 2

Barcode
1E 24

7hat is hidden behind the numbers cannot be made *isible by using a list bo6) as the oreign ,ey is input directly using the barcode. ?n the same way) it is impossible to use a list bo6 ne6t to the item to show at least the unit price. /ere a @uery can help. ')'&( "&hecKout"."Receipt_+,"" "&hecKout"."(otal"" " tocK"."+tem"" " tocK"."A%it_.rice"" "&hecKout"."(otal"I" tocK"."A%it_price" A "(otal_.rice" FROM "&hecKout"" "+tem" @1'R' " tocK"."+," E "&hecKout"."+tem_+,"5 "ow at least a ter the in ormation has been entered) we ,now how much needs to be paid or 3 H ?tem=1E=. ?n addition only the in ormation rele*ant to the corresponding 1eceiptL?2 needs to be iltered through the orm. 7hat is still lac,ing is what the customer needs to pay o*erall. ')'&( "&hecKout"."Receipt_+,"" AM*"&hecKout"."(otal"I" tocK"."A%it_price"4 A " um" FROM "&hecKout"" " tocK" @1'R' " tocK"."+," E "&hecKout"."+tem_+," 8ROA. !/ "&hecKout"."Receipt_+,"5 2esign the orm to show one record o the @uery at a time. .ince the @uery is grouped by 1eceiptL?2) the orm shows in ormation about one customer at a time.

#ata entry possibilities within ;ueries


To ma,e entries into a @uery) the primary ,ey or the table underlying the @uery must be present. This also applies to a @uery that lin,s se*eral tables together. ?n the loaning o media) it ma,es no sense to display or a reader items that ha*e already been returned some time ago. ')'&( "+,"" "Reader_+,"" "Media_+,"" ")oa%_date" FROM ")oa%" @1'R' "Retur%_,ate" + -A))5 ?n this way a orm can show within a table control ield e*erything that a particular reader has borrowed o*er time. /ere too the @uery must ilter using the appropriate orm structure &reader in the main orm) @uery in the subG orm() so that only media that are actually on loan are displayed. The @uery is suitable or data entry since the primary ,ey is included in the @uery. The @uery ceases to be editable) i it consists o more than one table and the tables are accessed *ia an alias. ?t ma,es no di erence in that case whether or not the primary ,ey is present in the @uery.

3hapter " Aueries

(!

')'&( "Media"."+,"" "Media"."(itle"" "&ate$ory"."&ate$ory"" "&ate$ory"."+," A "#at_+," FROM "Media"" "&ate$ory" @1'R' "Media"."&ate$ory_+," E "&ate$ory"."+,"5 This @uery is editable as both primary ,eys are included and can be accessed in the tables without using an alias. ')'&( "m"."+,"" "m"."(itle"" "&ate$ory"."&ate$ory"" "&ate$ory"."+," A "#at_+," FROM "Media" A "m"" "&ate$ory" @1'R' "m"."&ate$ory_+," E "&ate$ory"."+,"5 ?n this @uery the W4ediaW table is accessed using an alias. The @uery cannot be edited. ?n the abo*e e6ample) this problem is easily a*oided. ? ) howe*er) a correlated sub@uery &see page 14B( is used) you need to use a table alias. + @uery is only editable in that case i it contains only one table in the main @uery.

:se of parameters in ;ueries


? you o ten use the same basic @uery but with di erent *alues each time) @ueries with parameters can be used. ?n principle @ueries with parameters unction Rust li,e @ueries or a sub orm' ')'&( "+,"" "Reader+,"" "Media_+,"" ")oa%_date" FROM ")oa%s" @1'R' "Retur%_,ate" + -A)) A-, "Reader_+,"ED5 This @uery shows only the media on loan to the reader with the number 2. ')'&( "+,"" "Reader_+,"" "Media_+,"" ")oa%_date" FROM ")oa%s" @1'R' "Retur%_,ate" + -A)) A-, "Reader_+," E MReader%umber5 "ow when you run the @uery) an entry ield appears. ?t prompts you to enter a reader number. 7hate*er *alue you enter here) the media currently on loan to that reader will be displayed. 7hen using orms) the parameter can be passed rom the main orm to a sub orm. /owe*er it sometimes happens that @ueries using parameters in sub orms are not updated) i data is changed or newly entered. : ten it would be nice to alter the contents o list bo6es using settings in the main orm. .o or e6ample) we could pre*ent library media rom being loaned to indi*iduals who are currently banned rom borrowing media. #n ortunately controlling list bo6 settings in this personali0ed way by using parameters is not possible.

?ub;ueries
.ub@ueries built into ields can always only return one record. The ield can also return only one *alue. ')'&( "+,"" "+%come"" "'xpe%diture"" * ')'&( AM* "+%come" 4 F AM* "'xpe%diture" 4 FROM "&hecKout"4 A "!ala%ce" FROM "&hecKout"5 This @uery allows data entry &primary ,ey included(. The sub@uery yields precisely one *alue) namely the total balance. This allows the balance at the till to be read a ter each entry. This is still not comparable with the supermar,et chec,out orm described in IDueries as a basis or additional in ormation in ormsI. "aturally it lac,s the indi*idual calculations o Total H #nitLprice) but also the presence o the receipt number. :nly the total sum is gi*en. +t least the receipt number can be included by using a @uery parameter' ')'&( "+,"" "+%come"" "'xpe%diture"" * ')'&( AM* "+%come" 4 F AM* "'xpe%diture" 4 FROM "&hecKout" @1'R' "Receipt_+," E MReceipt_-umber4 A "!ala%ce" FROM "&hecKout" @1'R' "Receipt_+," E MReceipt_-umber5
(!! Base Handbook

?n a @uery with parameters) the parameter must be the same in both @uery statements i it is to be recogni0ed as a parameter. 5or sub orms such parameters can be included. The sub orm then recei*es) instead o a ield name) the corresponding parameter name. This lin, can only be entered in the properties o the sub orm) and not when using the 7i0ard.
.ub orms based on @ueries are not automatically updated on the basis o their parameters. ?t is more appropriate to pass on the parameter directly rom the main orm.

9ote

Correlated sub;ueries
#sing a still more re ined @uery) an editable @uery allows one to e*en carry the running balance or the till' ')'&( "+,"" "+%come"" "'xpe%diture"" * ')'&( AM* "+%come" 4 F AM* "'xpe%diture" 4 FROM "&hecKout" @1'R' "+," ;E "a"."+," 4 A "!ala%ce" FROM "&hecKout" A "a" OR,'R !/ "+," A & The Chec,out table is the same as Table WaW. WaW howe*er yields only the relationship to the current *alues in this record. ?n this way the current *alue o ?2 rom the outer @uery can be e*aluated within the sub@uery. Thus) depending on the ?2) the pre*ious balance at the corresponding time is determined) i you start rom the act that the ?2) which is an auto*alue) increments by itsel .

(ueries as source tables for ;ueries


+ @uery is re@uired to set a loc, against all readers who ha*e recei*ed a third o*erdue notice or a medium. ')'&( ")oa%"."Reader_+,"" GRrd Overdue S the reader is blacKlistedG A ")ocK" FROM * ')'&( &OA-(* ",ate" 4 A "(otal_&ou%t"" ")oa%_+," FROM "Recalls" 8ROA. !/ ")oa%_+,"4 A "a"" ")oa%" @1'R' "a".")oa%_+," E ")oa%"."+," A-, "a"."(otal_&ou%t" = D 5irst let us e6amine the inner ;uery) to which the outer @uery relates. ?n this @uery the number o date entries) grouped by the oreign ,ey %oanL?2 is determined. This must not be made dependent on the 1eaderL?2) as that would cause not only three o*erdue notices or a single medium but also three media with one o*erdue notice each to be counted. The inner @uery is gi*en an alias so that it can be lin,ed to the 1eaderL?2 rom the outer @uery. The outer ;uery relates in this case only to the conditional ormula rom the inner @uery. ?t shows only a 1eaderL?2 and the te6t or the %oc, ield when the W%oanW.W?2W and JaW.W%oanL?2W are e@ual and WaW.WTotalLCountW - 8 . ?n principle all ields in the inner @uery are a*ailable to the outer one. .o or e6ample the sum WaW.WTotalLCountW can be merged into the outer @uery to gi*e the actual ines total. /owe*er it can happen) in the Duery 2esign dialog) that the 2esign View 4ode no longer wor,s a ter such a construction. ? you try to open the @uery or editing again you get the ollowing warning'

3hapter " Aueries

(!"

? you then open the @uery or editing in .D% *iew and try to switch rom there into the 2esign View) you get the error message'

The 2esign View 4ode cannot ind the ield contained in the inner @uery W%oanL?2W) which go*erns the relationship between the inner and outer @ueries. 7hen the @uery is run in .D% 4ode) the corresponding content rom the sub@uery is reproduced without error. There ore you do not ha*e to use direct .D% mode in this case. The outer ;uery used the results o the inner ;uery to produce the inal results. These are a list o the W%oanL?2W *alues that should be loc,ed and why. ? you want to urther limit the inal results) use the sort and ilter unctions o the graphical user inter ace.

?ummariPing data with ;ueries


7hen data is searched or o*er a whole database) the use o simple orm unctions o ten leads to problems. + orm re ers a ter all to only one table) and the search unction mo*es only through the underlying records or this orm. !etting at all the data is simpler when you use @ueries) which can pro*ide a picture o all the records. The section on I1elationship de inition in the @ueryJ suggests such a @uery construction. This is constructed or the e6ample database as ollows' ')'&( "Media"."(itle"" " ubtitle"." ubtitle"" "Author"."Author" FROM "Media" )'F( LO+- " ubtitle" O- "Media"."+," E " ubtitle"."Media_+," )'F( LO+- "rel_Media_Author" O- "Media"."+," E "rel_Media_Author"."Media_+," )'F( LO+- "Author" O- "rel_Media_Author"."Author_+," E "Author"."+," /ere all WTitlesW) W.ubtitlesW and W+uthorsW are shown together. The 4edia table contains a total o > Titles. 5or two o these titles) there are a total o < .ubtitles. 7ithout a LE"T MOIN) both tables displayed together yield only < records. 5or each .ubtitle) the corresponding Title is searched or) and that is the end o the @uery. Titles without .ubtitle are not shown. "ow to show all 4edia including those without a .ubtitle' 4edia is on the le t side o the assignment) .ubtitle on the right side. + LE"T MOIN will show e*ery Title rom 4edia) but only a .ubtitle or those that ha*e a Title. 4edia becomes the decisi*e table or determining which records are to be displayed. This was already planned when the table was constructed &see
(!# Base Handbook

Chapter 3) Tables(. +s .ubtitles e6ist or two o the nine Titles) the @uery now displays > N < A 2 Y 1B records.
The normal lin,ing o tables) a ter all tables ha*e been counted) ollows the ,eyword 7/F1F.

9ote

? there is a LE"T MOIN or a RI+HT MOIN) the assignment is de ined directly a ter the two table names using ON. The se@uence is there ore always T)0&eE LE"T MOIN T)0&e8 ON T)0&eEH"%e&'E N T)0&e8H"%e&'E LE"T MOIN T)0&eG ON T)0&e8H"%e&'E N T)0&eGH"%e&'E HHH

Two titles o the 4edia table do not yet ha*e an author entry or a .ubtitle. +t the same time one Title has a total o three +uthors. ? the +uthor Table is lin,ed without a LE"T MOIN, the two 4edia without an +uthor will not be shown. 9ut as one medium has three authors instead o one) the total number o records displayed will still be 1B. :nly by using LE"T MOIN will the @uery be instructed to use the 4edia table to determine which records to show. "ow the records without .ubtitle or +uthor appear again) gi*ing a total o 1E records. #sing appropriate -oins usually increases the amount o data displayed. 9ut this enlarged data set can easily be scanned) since authors and subtitles are displayed in addition to the titles. ?n the e6ample database) all o the mediaGdependent tables can be accessed.

-ore rapid access to ;ueries using table views


Views in .D% are @uic,er than @ueries) especially or e6ternal databases) as they are anchored directly into the database and the ser*er returns only the results. 9y contrast @ueries are irst sent to the ser*er and processed there. ? a new @uery relates to another @uery) the .D% *iew in 9ase ma,es the other @uery loo, li,e a table. ? you create a View rom it) you can see that you are actually wor,ing with a sub@uery &.elect used within another .elect(. 9ecause o this) a Duery 2 that relates to another Duery 1 cannot be run by using Bdit 5 )un ?(+ command directly) since only the graphical user inter ace and not the database itsel ,nows about Duery 1. The database gi*es you no direct access to @ueries. This also applies to access using macros. Views) on the other hand) can be accessed rom both macros and tables. /owe*er) no records can be edited in a *iew. &They must be edited in a table or orm.(
+ @uery created using Create (uery in ?(+ 8iew has the disad*antage that it cannot be sorted or iltered using the !#?. There are there ore limits to its use.

$ip

+ Biew on the other hand can be managed in 9ase Rust li,e a normal table A with the e6ception that no change in the data is possible. /ere there ore e*en in direct .D%G commands all possibilities or sorting and iltering are a*ailable.

Views are a solution or many @ueries) i you want to get any results at all. ? or e6ample a .ubselect is to be used on the results o a @uery) create a 8iew that gi*es you these results. Then use the subselect on the View. Corresponding e6amples are to be ound in Chapter <) 2atabase Tas,s. Creating a View rom a @uery is rather easy and straight orward. 1( Clic, the $able obRect in the 2atabase section. 2( Clic, Create 8iew. 3( Close the +dd Table dialog.
3hapter " Aueries (!9

4( Clic, the 2esign View :n/:55 icon. &This is the .D% 4ode or a View.( B( !etting the .D% or the View' a( Fdit the @uery in .D% View. b( #se 3ontrol4> to highlight the @uery=s .D%. c( #se 3ontrol43 to copy the .D%. C( ?n the .D% 4ode o the View use 3ontrol4B to paste the .D%. E( Close) .a*e) and "ame the View.

(!)

Base Handbook

3hapter # 2eports

Creating reports using the )eport uilder


1eports are used to present data in a way that ma,es it readily understood by people without ,nowledge o the database. 1eports can'

T T T T

$resent data in easyGtoGread tables Create charts or displaying data 4a,e it possible to use data or printing labels $roduce orm letters such as bills) recall notices) or noti ications to people Roining or lea*ing an association

To create a report re@uires care ul preparatory wor, on the underlying database. #nli,e a orm) a report cannot include subreports and thus incorporate additional data sources. "either can a report present di erent data elements than those that are a*ailable in the underlying data source) as a orm can do using list bo6es. 1eports are best prepared using @ueries. ?n this way all *ariables can be determined. ?n particular) i sorting within the report is re@uired) always use a @uery that ma,es pro*ision or sorting. This means that @ueries in direct .D% mode should be a*oided under these conditions. ? you must use a @uery o this type in your database) you can carry out the sort by irst creating a *iew rom the @uery. .uch a *iew can always be sorted and iltered using the graphical user inter ace &!#?( o 9ase.
7hen using the 1eport 9uilder) you should re@uently sa*e your wor, during editing. ?n addition to sa*ing within the 1eport 9uilder itsel a ter each signi icant step) you should also sa*e the whole database. 2epending on the *ersion o %ibre: ice that you are using) the 1eport 9uilder can sometimes crash during editing. The unctionality o completed reports is not a ected e*en i they were created under another *ersion) in which the problem does not occur.

Caution

$he user interface of the )eport uilder


To start the 1eport 9uilder rom within 9ase) use )eports 5 Create )eport in #esign 8iew. The initial window o the 1eport 9uilder &5igure 4B( shows three parts. :n the le t is the current di*ision o the report into $age header) 2etail) and $age ooterP in the middle are the corresponding areas where the content will be enteredP and) to the right) the properties o these regions are shown. +t the same time the +dd ields dialog is displayed. This dialog corresponds to the one in orm creation. ?t creates ields with their corresponding ield labels. 7ithout content rom the database) a report has no proper unction. 5or this reason) the dialog opens at the 2ata tab. /ere you can set the content o the reportP in the e6ample it is the BiewL2eport:2ecall table. +s long as AnalyPe ?(+ command is set to Hes) the report can be subRected to sorting) grouping) and iltering. + *iew has been chosen or the basis o this report) so no ilter will be appliedP it has already been included in the @uery underlying the *iew.

("7

Base Handbook

'igure !": .nitial window of 2eport Builder Two output ormats or reports are a*ailable or selection' OD' *e1t document &a 7riter document( or OD' &preadsheet &a Calc document(. ? you Rust want a tabular *iew o your data) the Calc document should de initely be chosen or your report. ?t is signi icantly aster to create and is also easier to ormat subse@uently) as there are ewer options to consider and columns can easily be dragged to the re@uired width a terward. 9y de ault) the 1eport 9uilder loo,s or its data source in the irst table in the database. This ensures that at least a test o the unctions is possible. + data source has to be chosen be ore the report can be pro*ided with ields. The 1eport 9uilder pro*ides a lot o additional buttons) so the table on the ne6t page shows the buttons with their descriptions. The buttons or aligning elements are not urther described in this chapter. They are use ul or @uic, adRustment o ields in a single area o the 1eport 9uilder) but in principle e*erything can be done by direct editing o ield properties.

3hapter # 2eports

("(

Buttons for editin# content

Buttons for ali#nin# elements

-ust as with orms) it is help ul to use the appropriate na*igator. .o) or e6ample) a careless clic, at the start o the 1eport 9uilder can ma,e it di icult to ind the properties o the data or the report. .uch data may only be reachable through the report na*igator. %e tGclic, on 2eport and the properties o the report are once more accessible.

("8

Base Handbook

?nitially the na*igator shows) in addition to the *isible sections o the document &$age header) !roups) 2etail) and $age ooter() the possibility o including unctions. !roups can be used) or e6ample) to assign all media being recalled to the person who has borrowed them) to a*oid multiple recall notices. 2etail areas show the records belonging to a group. 5unctions are used or calculations such as sums. To obtain use ul output in the abo*e e6ample) the content o the *iew must be reproduced with suitable grouping. Fach reader should be lin,ed to the recall notices or all o their loaned and o*erdue media. 8iew 5 ?orting and 6rouping or the corresponding button starts the grouping unction.

'igure !#: &orting and %rouping /ere grouping and sorting are by the 2eader:?ame ield. +dditional ields could also be included in the table abo*e. 5or e6ample) i you also want to group and sort by the Loan:Date ield) choose this as the second line. 2irectly under the table) se*eral grouping actions are a*ailable or selection. You can mo*e a group up or down the list or completely remo*e it. +s only one group is necessary or the planned report) 5igure 4C shows only the Delete symbol at the e6treme right o the group actions as a*ailable. The &orting property is sel Ge6planatory. 7hen the entry was created) the le t side o the 1eport 9uilder immediately showed a new di*ision. "e6t to the ield description 2eader:?ame you can now see Header. This section is or the group header in the report. The header might contain the name o the person who will recei*e the recall notice. ?n this case there is no group ooter. .uch a ooter could contain the ine due) or the place and current date and a space or the signature o the person sending the notice.

3hapter # 2eports

("

9y de ault there is a new group or each *alue. .o i the 2eader:?ame changes) a new group is started. +lternati*ely you can group by initial letter. ?n the case o a recall notice) howe*er) this would put all readers with the same initial together in one group. .chmidt) .chul0e) and .chulte would recei*e a common recall notice) which would be @uite pointless in this e6ample. 7hen grouping by initial letter) you can additionally speci y how many letters later the ne6t group should begin. :ne can imagine or e6ample a grouping or a small telephone directory. +ccording to the si0e o the contact list) one might imagine a grouping on e*ery second initial letter. .o + and 9 would orm the irst group) then C and 2) and so on. + group can be set either to be ,ept together with the irst details section) or) as ar as possible) as a complete group. 9y de ault) this option is set to ?o . 5or recall notices) you would probably want the group to be arranged so that a separate page is printed or each person who is to recei*e a recall letter. ?n another menu) you can choose that each group &in this case) each reader name( be ollowed by a page brea, be ore dealing with the ne6t *alue. ? you ha*e chosen to ha*e a group header and perhaps a group ooter) these elements will appear as sections in the report na*igator under the corresponding ieldname 2eader:?ame. /ere too you ha*e the possibility o using unctions) which will then be limited to this group. To add ields) use the >dd field unction) as with orms. /owe*er in this case) the label and the ield contents are not tied together. 9oth can be independently mo*ed) changed in si0e and dragged to di erent sections.

'igure !9: 2eport design for e1ample recall notice 5igure 4E shows the report design or the recall notice. ?n the page header is the heading %ibre : ice %ibrary) inserted as a label ield. /ere you could also ha*e a letterhead with a logo) since the incorporation o graphics is possible. The act that this le*el is called $age header does not imply that there is no space abo*e it. That depends on the page settingsP i an upper margin has been set) it lies abo*e the page header.
("! Base Handbook

2eader:?ame header is the header or the grouped and sorted data. ?n the ields that are to contain data) the names o the corresponding data ields are shown in light gray. .o) or e6ample) the *iew underlying the report has a ield named +ddress) containing the complete address o the recipient with street and town. To put this into a single ield re@uires line brea,s in the @uery. You can use CHAR(EG) to create them. F6ample' ')'&( "First-ame"77G G77")ast-ame"77&1AR*CR477" treet"77G G77"-o"77 &1ARCR77".ostcode"77G G77"(ow%" FROM "First-ame" The Q*OD>H56 ield represents a builtGin unction) which inserts the current date into this position. ?n 2eader:?ame header) in addition to the salutation) we see the column headings or the ollowing table *iew. These elements should appear only once) e*en i se*eral media are listed. ?n the bac,ground o these column headers is a gray rectangle) which also ser*es as a rame or the data. The details area is repeated as o ten as there are separate records with the same 2eader:?ame data. /ere are listed all media that ha*e not been returned on time. There is another rectangle in the bac,ground to rame the contents. This rectangle is illed with white rather than gray.
?n principle %ibre: ice pro*ides or the possibility o adding hori0ontal and *ertical lines. These are displayed in design mode. +t present they do not appear when the report is complete.

9ote

These lines ha*e the urther disad*antage that they are interpreted only as hairlines. They can be reproduced better i rectangles are used. .et the bac,ground o the rectangle to blac, and the si0e to) or e6ample) 1Ecm wide and 0.03cm high. This will create a hori0ontal line with a thic,ness o 0.03cm and a length o 1Ecm.

The 2eader:?ame footer closes the letter with a greeting ormula and an area or the signature. The ooter is so de ined that an additional page brea, will occur a ter this area. +lso) contrary to the de ault setup) it is speci ied that this area should be ,ept together in all cases. + ter all) it would loo, rather odd i many recall notices had the signature on a separate page. Eeep together re ers here to the page brea,. ? you want the content o a record to be ,ept together independently o the brea,) this is only possible at present i the record is not read in as 2etails but is used as the basis or a grouping. You can choose Eeep together Q Hes) but it does not wor,P the 2etails area becomes separated. You ha*e to put the content o 2etails in a separate group to ,eep it together. + builtGin unction is used or calculating the total ines.
3hapter # 2eports (""

9elow is what an actual recall notice would loo, li,e. The details area contains B media that the reader has ta,en out on loan. The group ooter contains the total ine due.

9ote

1eports or single records can also e6tend o*er more than one page. The si0e o the report is @uite separate rom the page si0e. /owe*er) stretching the details area o*er more than one page can lead to aulty brea,s. /ere the 1eport 9uilder still has problems in calculating the spacing correctly. ? both grouping areas and graphical elements are included) this may result in unpredictable si0es or certain areas. .o ar indi*idual elements can be mo*ed to positions outside the si0e o a single page only with the mouse and cursor ,eys. The properties o the elements always pro*ide the same ma6imum distance rom the upper corner o any area that lies on the irst page.

("#

Base Handbook

6eneral properties of fields


There are only three types o ield or the presentation o data. ?n addition to te6t ields &which) contrary to their name) can also contain numbers and ormatting() there is also a ield type that can contain images rom the database. The chart ield displays a summary o data.

+s with orms) ields are gi*en names. 9y de ault) the name is that o the underlying database ield. + ield can be set to be in*isible. This may seem a bit pointless in the case o ields but is use ul or group headers and ooters) which may be re@uired to carry out other unctions o the grouping without containing anything that needs to be displayed. ? $rint repeated values is deacti*ated) display o the ield is inhibited when a ield with the same content is loaded directly be ore. This unctions correctly only or data ields that contain te6t. "umeric ields or date ields ignore the deacti*ation instruction) %abel ields are completely aded out when deacti*ated) e*en i they occur only once. ?n the 1eport 9uilder the display o certain content can be inhibited by using 3onditional $rint <1pression or the *alue o the ield can be used as a base or ormatting te6t and bac,ground. 4ore on conditional e6pressions is gi*en in IConditional printJ on page 1C>. The setting or the mouse wheel has no e ect because report ields are not editable. ?t seems to be a le to*er rom the orm de inition dialog. The $rint Dhen %roup 3hange unction could not be reproduced in reports either. ? the bac,ground is not de ined as transparent) a bac,ground color can be de ined or each ield. The other entries deal with the internal content o the ield in @uestion. This co*ers the ont & or ont color) ont weight) and so on) see 5igure 4<() the alignment o the te6t within the ield) and ormatting with the corresponding Character dialog &see 5igure 4>(.

3hapter # 2eports

("9

'igure !): 'onts: 3haracter &ettings

'igure !,: 'ormatting numbers

(")

Base Handbook

& ecial ro erties of #ra hical controls

+ graphical control can contain graphics rom both inside and outside the database. #n ortunately it is not possible at present to store a graphic such as a logo permanently in 9ase. There ore it is essential that the graphic is a*ailable in the search path) e*en when you are presented with the choice o embedding rather than lin,ing images and the irst ield &et up as link can be set &literally closed( to a corresponding planned unctionality. This is one o se*eral unctions that are planned or 9ase and are in the !#? but ha*e not actually been implemented yetSso the buttons and chec,bo6es ha*e no e ect. +lternati*ely) o course) a graphic can be stored in the database itsel and so becomes a*ailable internally. 9ut in that case) it must be accessible through one o the ields in the @uery underlying the report. To ta,e up an e1ternal graphicI use the selection button beside the %raphic ield to load it. To load a graphical database ield) speci y the ield under the Data tab. The *ertical alignment setting does not seem to ha*e any e ect during the design stage. 7hen you call up the report) howe*er) the graphic appears in the correct position. 7hen scaling) you can select ?o) Eeep aspect ratio) or >utom. &i/e. This corresponds to the settings or a orm'

T T T

?o' The image is not itted to the control. ? it is too large) a cropped *ersion is shown. The original image is not a ected by this. Eeep aspect ratio' The image is itted to the control but not distorted. >utomatic si/e' The image is itted to the control and in some cases may be distorted.

3hapter # 2eports

(",

)ncor oratin# charts into the re ort


You can insert charts into a report by using the corresponding control or with Insert 5 )eport controls 5 Chart. + chart is the only way to reproduce data that is not ound in the data source speci ied or the report. + chart can there ore be seen as a ,ind o subreport) but also as a reeG standing component o the report.

You must draw the place or the chart using the mouse. ?n the general properties) in addition to the amiliar ields) you can choose a 3hart t0pe &see the corresponding types in Calc(. ?n addition) you can set a ma6imum number o records or the pre*iew) which will gi*e an impression o how the chart will inally loo,. Charts can be ormatted in the same way as in Calc &doubleGclic, on the chart(. 5or urther in ormation) see the description in the LibreOffice 3alc %uide.

The chart is lin,ed in the 2ata section with the necessary data ields. /ere) in a 4edia Top 10 list e6ample) the chart shows the re@uency with which particular media are borrowed. The Duery Fditor is used to create a suitable .D% command) as you would do or a listbo6 in a orm. The irst column in the @uery will be used to pro*ide the labels or the *ertical bars in the chart) while the second column yields the total number o loan transactions) shown in the height o the bars. ?n the e6ample abo*e) the chart shows *ery little at irst) since only limited test loans were carried out be ore the .D% command was issued. The chart on the ne6t page) rom the membership database o a society &!erman' 4itgliederstatisti,() has been prepared rom a @uery that needs to be entered in direct .D% mode) as the graphical user inter ace does not understand it. 5or this reason ?o &!erman' "ein( has been chosen or >nal0/e &AL command) a choice that e6cludes any iltering and sorting with the internal tools o the 1eport 9uilder. These ields are there ore grayed out. ?n the data properties o the chart) (uery &!erman' +b rage( has been entered. 5ields are lin,ed together in the same way as or a main orm with a sub orm. ?n the report itsel ) the age distributions o male and emale members are listed in tabular orm. They are grouped by gender. Fach group is gi*en its own chart. .o that the chart only contains data or the correct gender) the %ender ield &!erman' !eschlecht( in the report is lin,ed to the %ender in the chart.

(#7

Base Handbook

'igure "7: Linked fields for a chartI same as in forms. *his e1ample is not translatedI because the report is nt part of the e1ample database.
The creation o charts wor,s at present only in Versions 3.3.6 and 3.4.6. 5rom Version 3.B) %ibre: ice can no longer open these reports. They can still be produced) howe*er. %ibre: ice is not the only program to ha*e problems with charts. ?n Version 3.3 o :pen: ice.org) the display does not wor, either. :pen: ice.org does open the reports) but with the charts missing.

9ote

#ata properties of fields

?n the properties dialog) the 2ata tab shows by de ault only the database ield rom which the data or this report ield will be read. /owe*er) in addition to the ield types 'ield and 'ormulaI the types 'unction) 3ounterI and +ser-defined function are a*ailable. You can select in ad*ance the &umI ;inimumI and ;a1imum unctions. They will apply either to the current group or to the whole report. These unctions can lead to problems i a ield is empty &"#%%(. ?n such ields) i they ha*e been ormatted as numbers) W"a"W appearsP that is) there is no numerical *alue present. 5or empty ields) no calculation is carried out and the result is always 0. .uch ields can be re ormatted to display a *alue o 0 by using the ollowing ormula in the 2ata area o the *iew. +F*6%umeric<ield956%umeric<ield9534 This unction calculates with the actual *alue o a ield that has no *alue. ?t would seem simpler to ormulate the underlying @uery or the report so that 0 is gi*en instead o "#%% or numeric ields.

3hapter # 2eports

(#(

The 3ounter counts only the records that will occur either in the group or in the report as a whole. ? the counter is inserted into the 2etails area) each record will be pro*ided with a running number. The numbering will apply only to records in the group or in the whole report.

5inally the detailed +ser-defined 'unction is a*ailable. ?t may happen that the 1eport 9uilder itsel chooses this *ariant) i a calculation has been re@uested) but or some reason it cannot correctly interpret the data source.

Functions in the )eport uilder


The 1eport 9uilder pro*ides a *ariety o unctions) both or displaying data and or setting conditions. ? these are not su icient) userGde ined unctions can be created using simple calculation steps) which are particularly use ul in group ooters and summaries.

Bntering formulas
The 1eport 9uilder is based on the $entaho 1eport 9uilder. + small part o its documentation is at http'//wi,i.pentaho.com/display/1eporting/>.N1eportN2esignerN5ormulaNF6pressions. + urther source is the .peci ications or the :pen5ormula .tandard' http'//www.oasisGopen.org/committees/download.php/1C<2C/open ormulaGspecG200C0221.html 9asic principles' 5ormulas start with an e@uals sign. 1e erences to data ields are placed in s@uare brac,ets. ? the data ields contain special characters &including spaces() the ield name must also be enclosed in @uotes. Te6t entry must always be in double @uotes. The ollowing operators are allowed. N 2"%e&' ()*e6 2"T.%s C%e&'()*e s.-=&' 0e %( O=-tes"6 "Text e(t/J" N) G) H &4ultiplication() / &2i*ision() V &di*ide the preceding number by 100() f &1aise to the power o the ollowing number() O &concatenate te6t() N , ,1 , , , ,N , 1 , 1N ( ) NA &"ot a*ailable( N)N &$erhaps Wnot a numberW;(

The ollowing relationships are possible. 1ound brac,ets are allowed. 2e ault error message. Frror message or an empty ield that was de ined as a number.

(#8

Base Handbook

+ll ormula input applies only to the current record. 1elationships with pre*ious or ollowing records are there ore not possible.

"e6t to the date ield is a button with three dots whene*er a ormula can be entered. This button starts the 5unction 7i0ard.

/owe*er there are ar ewer unctions than in Calc. 4any unctions do ha*e Calc e@ui*alents. There the 7i0ard calculates the result o the unction directly. The 5unction 7i0ard does not always wor, per ectly. 5or instance) te6t entries are not ta,en up with double @uotes. /owe*er) only entries with double @uotes are processed when starting the unction. The ollowing unctions are a*ailable' 'unction %ate and $ime 'unctions DATE DATEDI" 5D>H R ;O?*H R H<>26 DATEVALUE
$roduces a *alid date rom numeric *alues or the year) the month and the day. 1eturns the total years) months or days between two date *alues. Con*erts an +merican date entry in te6t orm &@uoted( into a date *alue. The +merican *ariant that is produced can then be re ormatted. 1eturns the day o the month or a gi*en date. 2+Y&_2ate ield`(

%escri tion

DAY

3hapter # 2eports

(#

DAY HOUR MINUTE MONTH NO! ECOND

1eturns the number o days between two dates. 1eturns the hours o a gi*en time in 24Ghour ormat. /:#1&_2ateTime5ield`( calculates the hours in the ield. 1eturns the minutes o a date in the internal numeric ormat 4?"#TF&_Time ield`( calculates the minutes part o the time. 1eturns the month or an entered date as a number. 4:"T/&_2ate ield`( 1eturns the current date and time. 1eturns the seconds o a date in the internal numeric ormat .FC:"2&":7&(( shows the seconds part o the time the command is e6ecuted. .hows the current time. Con*erts a te6t entry or a time into a time *alue or calculations. .hows the current date. 1eturns the day o the wee, as a number. 2ay number 1 is .unday. 1eturns the year part o a date entry.

TIME TIMEVALUE TODAY !EEKDAY YEAR Lo#ical functions AND "AL E I" I"NA NOT OR TRUE XOR /oundin# functions INT Mathematical functions AB ACO

Yields T1#F when all its arguments are T1#F. 2e ines the logical *alue as 5+%.F. ? a condition is T1#F) then this *alue) else another *alue. &since %: 3.B( 1e*erses the logical *alue o an argument. Yields T1#F when one o its conditions is T1#F. 2e ines the logical *alue as T1#F. Yields T1#F when only one o the lin,ed *alues is T1#F.

1ounds down to the pre*ious integer.

1eturns the absolute &nonGnegati*e( *alue o a number. Calculates the arccosine o a number. G arguments between G1 and 1. &since %: 3.B( Calculates the areacosine &in*erse hyperbolic cosine( A argument [Y 1. &since %: 3.B( Calculates the arcsine o a number A argument between G1 and 1. &since %: 3.B(

ACO H

A IN

(#!

Base Handbook

ATAN ATAN8 AVERA+E AVERA+EA CO EVEN EXP LN LO+E0 MAX MAXA MIN MINA MOD ODD PI PO!ER IN $RT UM UMA

Calculates the arctangent o a number. &since %: 3.B( Calculates the arctangent o an 6Gcoordinate and a yGcoordinate. &since %: 3.B( !i*es the a*erage o the entered *alues. &occurs twice in the %: 3.3.4 5ormula 7i0ard( !i*es the a*erage o the entered *alues. Te6t is treated as 0ero. &since %: 3.B( +rgument is the angle in radians whose cosine is to be calculated. &since %: 3.B( 1ounds a positi*e number up or a negati*e number down to the ne6t e*en integer. Calculates the e6ponential unction &9ase =e=(. &since %: 3.B( Calculates the natural logarithm o a number. &since %: 3.B( Calculates the logarithm o a number &9ase =10=(. &since %: 3.B( 1eturns the ma6imum o a series o numbers. 1eturns the ma6imum *alue in a row. +ny te6t is set to 0ero. 1eturns the smallest o a series o *alues. 1eturns the minimum *alue in a row. +ny te6t is set to 0ero. 1eturns the remainder or a di*ision when you enter the di*idend and di*isor. 1ounds a positi*e number up or a negati*e number down to the ne6t odd integer. !i*es the *alue o the number =g=. &since %: 3.B( 1aises the base to the power o the e6ponent. &.ince %: 3.B( Calculates the sine o a number. &since %: 3.B( Calculates the s@uare root o a number. &since %: 3.B( .ums a list o numeric *alues .ums a list o numeric *alues. Te6t and Yes/"o ields are allowed. #n ortunately this unction &still( ends with an error message. &since %: 3.B( Calculates the *ariance) starting rom a sample. &since %: 3.B(

VAR

3hapter # 2eports

(#"

$ext functions EXACT "IND LE"T LEN LO!ER ME MID REPLACE REPT RI+HT UB TITUTE A+E
.hows i two te6t strings are e6actly e@ual. !i*es the o set o a te6t string within another string. The speci ied number o characters o a te6t string are reproduced starting rom the le t. !i*es the number o characters in a te6t string. Con*erts te6t to lower case. 5ormats the *alue into the gi*en output ormat. &since %: 3.B( The speci ied number o characters o a te6t string are reproduced starting rom a speci ied character position. 1eplaces a substring by a di erent substring. The starting position and the length o the substring to be replaced must be gi*en. 1epeats te6t a speci ied number o times. The speci ied number o characters o a te6t string are reproduced starting rom the right. 1eplaces speci ic parts o a gi*en te6t string by new te6t. +dditionally you can speci y which o se*eral occurrences o the target string are to be replaced. 1eturns the te6t) or an empty te6t string i the *alue is not te6t & or e6ample a number(. Con*ersion o numbers or times into te6t. 1emo*es leading spaces and terminal spaces) and reduces multiple spaces to a single space. Con*erts a #nicode decimal number into a #nicode character. 5or e6ample) 1>C becomes =h= &=h= has the he6adecimal *alue 00C4) which is 1>C in decimals without leading 0eros(. Con*erts a #nicode character into a #nicode decimal number. =h= becomes 1>C. 1eturns a te6t string in upper case. Con*erts a gi*en te6t into one that con orms to a *alid #1%. ? no particular standard is speci ied) ?.:G<<B>G1 is ollowed.. The irst argument is an inde6) ollowed by a list o *alues. The *alue represented by the inde6 is returned. CHOO E(8F"A<<&e"F"Pe)/"F"B)()()") returns Pe)/. CHOO E(2)Be_&e:e&_C%e&'6F"M%&9"F"C-&)"F"Bee/") returns a possible drin, or the gi*en =age:level:fieldS . :nly ields containing a number or a date are counted. COUNT(2t%*e6F2(=*0e/6) returns 8) i both ields contain a *alue &nonG"#%%( or else 1 or 0. ?ncludes also ields containing te6t. F*en "#%% is counted) along with boolean ields.
Base Handbook

T TEXT TRIM UNICHAR

UNICODE UPPER URLENCODE )nformation functions CHOO E

COUNT

COUNTA

(##

COUNTBLANK HA CHAN+ED INDEX I BLANK I ERR I ERROR I EVEN I LO+ICAL 5.&*LO%6 I NA I NONTEXT I NUMBER I ODD I RE" I TEXT NA 5?B6 VALUE !ser defined C VARRAY C VTEXT NORMALIQEARRAY NULL PAR EDATE

Counts the empty ields in a region. Chec,s i the named column has changed. /owe*er no in ormation about the column is pro*ided. 7or,s with regions &since %: 3.B(. Tests i the ield is "#%% &empty(. 1eturns T1#F i the entry has an error other than "+. I ERR(EP0) gi*es TRUE %i,e ?.F11) e6cept that "+ also returns T1#F. Tests i a number is e*en. Tests i this is a Yes/"o *alue. I LO+ICAL(TRUE()) or I LO+ICAL("AL E()) yield TRUE) Te6t *alues such as I LO+ICAL("TRUE") yield "AL E. Tests i the e6pression is an error o type "+. Tests i the *alue is not te6t. Tests i something is numeric. I NUMBER(E) yields TRUE) I NUMBER("E") yields "AL E Tests i a number is an odd number. Tests i something is a ield re erence. I RE"(2"%e&'()*e6) yields TRUE) I RE"(E) yields "AL E. Tests i the content o the ield is te6t. 1eturns the error code NA. &since %: 3.B(

Con*erts C.V te6t into an array. &since %: 3.B( Con*erts an array into C.V te6t. &since %: 3.B( &since %: 3.B( 1eturns "#%%. Con*erts te6t into a date. #ses the .imple2ate5ormat. 1e@uires a date in te6t as described in this date ormat. F6ample' $+1.F2+TF&W>.10.2012WPWdd.44.yyyyW( yields the internally usable number or the date. &since %: 3.B( +uthor) as read rom the $ools M 4ptions M +ibre4ffice M :ser data. This is not there ore the actual author but the current user o the database. 1eturns the title o the report.

%ocument information AUTHOR

TITLE

3hapter # 2eports

(#9

:serQdefined functions
You can use userGde ined unctions to return speci ic intermediate results or a group o records. ?n the abo*e e6ample) a unction o this sort was used to calculate the ines in the 2eader:?ame:'ooter area.

?n the 1eport "a*igator the unction is displayed under 2eader:?ame group. 9y rightGclic,ing on this unction) you can de ine additional unctions by name. The properties o the unction &umme%ebuehrLeser:?ame are shown abo*e. The ormula adds the ield 3harge to the *alue already stored in the unction itsel . The initial *alue is the *alue o the 3harge ield on the irst tra*erse o the group. This *alue is stored in the unction under the unction name and is reused in the ormula) until the loop is ended and the group ooter is written. Deep traversing seems to ha*e no unction or now) unless charts are being treated here as subreports. ? $re evaluation is acti*ated or the unction) the result can also be placed in the group header. :therwise the group header contains only the corresponding *alue o the irst ield o the group. #serGde ined unctions can also re erence other userGde ined unctions. ?n that case you must ensure that the unctions used ha*e already been created. $reGcalculation in unctions that re er to other unctions must be e6cluded. 6 umMarKs&lass9 / *6&lass-umber9HC4 re ers to the 3lass group. The content o the ;arks ield is summed and the sum or all the records is returned. The sum o the mar,s is di*ided by the sum o the records. To get the correct number) 1 must be added as shown with F3lass?umberG. This will then yield the a*erage mar,s.

(#)

Base Handbook

Formula entry for a field


#sing #ata 5 #ata field you can enter ormulas that a ect only one ield in the 2etails area. +F*6boolea%_<ield95"/es"5"No"4 sets the allowable *alues to WYesW or W"oW instead o T1#F and 5+%.F.

Conditional print

The general properties o group headers) group ooters) and ields include a Conditional $rint <1pression ield. 5ormulas that are written in this ield in luence the content o a ield or the display o an entire region. /ere) too) you can ma,e use o the 5unction 7i0ard. 6Field%ame9E"true" causes the content o the named ield to be displayed only i it is true. 4any orms o conditional display are not ully determined by the speci ied properties. 5or instance) i a graphical separator line is to be inserted a ter the tenth place o a list o competition results) you cannot simply use the ollowing conditional display command or the graphic' 6.lace9EC3 This command does not wor,. ?nstead the graphic will continue to appear in the Details section a ter each subse@uent record. ?t is sa er to bind the conditional display to a group footer rather than to the graphic) i this is not otherwise needed. The line is positioned in the group footer. Then the line does actually appear a ter the 10th place) when ormulated as abo*e. 9ut in that case the content that would pre*iously ha*e appeared in the Details section must be stored in the group header.

Conditional formatting
Conditional ormatting can be used) or e6ample) to ormat a calender so that wee,ends are shown di erently. Choose Format 5 Conditional formatting and enter' @''#,A/*6,ate94EC and the corresponding ormatting or .undays. ? you use cF6pression isK in conditional ormatting) you can enter a ormula. +s is usual in Calc) se*eral conditions can be ormulated and are e*aluated se@uentially. ?n the abo*e e6ample) irst .unday is tested or) then .aturday. 5inally there might be a @uery about the content o the ield. .o or e6ample the content c/olidayK would lead to a di erent ormat.

3hapter # 2eports

(#,

9ote

The 1eport 9uilder is a plugGin. ? additional uncorrectable errors occur & ormulas not implemented) too long te6t shown as an empty ield) and so on() it is sometimes necessary to delete parts o the report or simply create it a resh.

(97

Base Handbook

3hapter 9 Linking to Databases

6eneral notes on database linkage


9ase allows you to use documents in %ibre: ice 7riter and Calc in *arious ways as data sources. This means that the use o 9ase is not necessarily tied to the registration o databases in the con iguration o %ibre: ice. F6ternal orms can also interact directly with 9ase) pro*ided that the path to the data sources is supplied.

)egistration of databases
4any unctions) such as printing labels or using data or orm letters) re@uire the registration o a database in the con iguration o %ibre: ice. #sing $ools 5 4ptions 5 +ibre4ffice ase 5 #atabases 5 9ew) a database can be registered or subse@uent use by other %ibre: ice components.

The database is ound using the ile browser and connected to %ibre: ice in a similar way as or a simple orm. The database itsel must be gi*en a suitably in ormati*e name) or which you can simply use the name o the database ile. The name ser*es as an alias) which can also be used in @ueries to the database.

#ata source browser


The data source browser allows you access to tables and @ueries o all registered databases under their registered names. The browser can be opened using 8iew 5 #ata sources) or by pressing the '! ,ey) or by using the corresponding symbol in the standard toolbar.

(98

Base Handbook

1egistered data sources are shown on the le t side o the data source browser. The 9ibliography data source is included in %ibre: ice by de ault. The other data sources are listed by their registered names.

+ clic, on the e6pansion sign in ront o the database name opens the database and shows a subG older or @ueries and another or tables. :ther subG olders o the database are not made a*ailable here. ?nternal orms and reports can only be accessed by opening the database itsel . :nly when you clic, on the Tables older is the database actually accessed. 5or databases protected by a password) the password must be entered at this point. To the right o the name tree) you can see the table you ha*e selected. ?t can be edited Rust as in 9ase. /owe*er direct entry into tables should be carried out with caution in *ery comple6 relational databases) as the tables are lin,ed together with oreign ,eys. 5or e6ample) the database shown below has separate tables or street names) postcodes and towns. 5or a proper *iew o the data &but without the ability to edit() @ueries or *iews are more suitable.

: the icons in the toolbar) many will be amiliar rom data entry into tables. The main new ones are those in the last section' Data to *e1tI Data to 'ieldsI ;ail ;ergeI Data &ource of 3urrent DocumentI <1plorer on/off.

3hapter 9 Linking to Databases

(9

'igure "(: Data source browser toolbar

#ata to $e/t
The Data to *e1t unction is a*ailable as soon as a record is selected.

'igure "8: &electing a data record ? you now choose 2ata to Te6t) a 7i0ard appears to carry out the necessary ormatting.

(9!

Base Handbook

'igure " : Data entr0 as table There are se*eral possibilities or entering data as te6t' as a table) as single ields) or as ordinary te6t. The igure abo*e shows the option Insert #ata as $able. ?n the case o numeric and date ields) the database ormat can be changed to a chosen ormat. :therwise) ormatting is carried out automatically when the table ields are selected. The se@uence o ields is adRusted by using the arrow ,eys. +s soon as table columns ha*e been selected) the $roperties button or the table is acti*ated. This allows you to set the usual table properties or 7riter &table width) column width) and so on(. The chec,bo6 determines i a table header is re@uired. ? it is not chec,ed) no separate row will be reser*ed or headings. The row chosen or the table headings can be ta,en rom the column names) or the record may be written out with space le t or the headings to be edited in later. The +uto5ormat button pro*ides se*eral preG ormatted table *iews. +part rom the suggested Default ormat) all the ormats can be renamed. To add an auto ormat) a table in this ormat must irst be created. This is then selected and can be added to the list by using the >dd button. The table is inally created with the selected columns.

3hapter 9 Linking to Databases

(9"

'igure "!: >uto'ormat provides a choice of table formats Insert data as Fields pro*ides the possibility o using a miniGeditor to position the *arious table ields successi*ely in the te6t. The te6t created in this way can also be pro*ided with a paragraph style. ?n this case too) the ormatting o dates and numbers can be speci ied separately) or can be read directly rom the table settings in the database.

'igure "": .nsert data as 'ields C corresponds also to the dialog for .nsert data as *e1t The ields inserted into the te6t in this way can subse@uently be deleted singly or used or a mail merge. ? you choose Insert data as $e/t) the only di erence rom using ields is that ields remain lin,ed to the database. 7hen you insert as te6t) only the content o the speci ied ields is trans erred and not the lin, to the actual database. That e6plains why the dialog or this option is the same as or the pre*ious one.
(9# Base Handbook

The results o the two procedures are compared below.

'igure "#: 3omparison of Data as 'ields and Data as *e1t The ields ha*e a gray bac,ground. ? the mouse is ho*ered o*er the ields) it shows that the ields are lin,ed to the ;edia database) to the table 2eader and) within this table) to the ield .D. .o) or e6ample) a doubleGclic, on the ield .D opens the ollowing o*er*iew. This ma,es it clear which ield was created through the .nsert Data as 'ields procedure. ?t is the same ield type that is shown by Insert 5 Fields 5 4ther 5 #atabase.

'igure "9: Double-click on an inserted field to show the properties of the ;ail ;erge fields ?t is simpler to create such a ield by selecting the column header o the table in the data source browser and dragging it into the document with the mouse. You can create a orm letter directly in this way.

#ata to Fields
Data as 'ields) as described in the pre*ious section) is used to create mail merge ields in a 7riter document. ? now you select a di erent record in the data source browser and then choose Data as 'ields) the pre*iously inserted data are replaced by the new data.

3hapter 9 Linking to Databases

(99

/ere another record has been selected. 7hile the .nsert data as 'ields option leads to the pre*ious *alues being changed to the *alues or the new record) in the case o .nsert data as *e1t) the e6isting te6t remains unchanged.

-ail merge
The ;ail ;erge button launches the 4ail 4erge 7i0ard. +s the orm letter in the abo*e e6ample assembles its data rom di erent tables) you need irst to launch the database. ?n the database) you then create a new @uery to ma,e the re@uired data a*ailable.

The database is launched through a rightGclic, on the database itsel or on one o its tables or @ueries) which immediately re reshes the display in the data source browser. + ter that the 4ail 4erge 7i0ard can be called up by using the corresponding button.

#ata source of current document


+ clic, on the Data &ource of 3urrent Document button opens a direct *iew on the table which orms the basis or the data inserted into the document. ?n the abo*e e6ample) the $erson table rom the >ddresses database appears.

B/plorer onOoff
Toggling the <1plorer On/Off button shows or hides the directory tree to the le t o the table *iew. This allows more space) i necessary) or a display o the data. To access another table) you will need to switch the F6plorer bac, on.

Creating mail merge documents


The 4ail 4erge 7i0ard is also accessible rom the database browser. This 7i0ard allows the address ield and the salutation to be constructed rom a data source in small steps. ?n principle you can create these ields without using the 7i0ard. /ere we will wor, through the steps o the 7i0ard as an e6ample.

(9)

Base Handbook

The ?tarting document or the orm letter is the document to which the database fields are linked. The -erged document is the one containing the data or the *arious people who are to recei*e the orm letters. ?n the merged document there is no linkage to the data source. ?t is similar to the output o .nsert Data as *e1t.

The 4ail 4erge 7i0ard can produce either letters or emails using records rom the database.

3hapter 9 Linking to Databases

(9,

The entry o the address bloc, allows the most e6tensi*e con iguration. The suggested address list comes rom the currently selected @uery or table in the currently selected database. .tep 2 determines the o*erall loo, o the address bloc,. This address bloc, can be customi0ed urther using the ;ore button. .ee the ollowing igure. .tep 3 ser*es to lin, the named ields in the address bloc, to the correct ields in the database. The 7i0ard initially recogni0es only those database ields which ha*e e6actly the same names as those the 7i0ard uses. ?n .tep 4) the addresses are displayed. You can choose which addresses to ta,e rom the database by using the arrow ,eys. ?n the displayed addresses two elements re@uire urther editing' +part rom the irst name) all the other ields are L not 0et allocated - ) because the ield names in the database are di erent rom the names that the 7i0ard initially uses. To correct these errors) the address bloc, rom .tep 2 must be made editable.

T T

There is no salutation.

()7

Base Handbook

You can see in the bac,ground that) when you choose to edit) you are irst presented with an enlarged list o address bloc,s. /ere you can select the most suitable address bloc, to start with) and then edit it. The address bloc, cannot be edited directly. ?nstead) the arrangement o the ields is carried out by using the arrow buttons *isible to the right to mo*e ields into or out o the address bloc, 5or the salutation the &alutation ield is inserted. +ll the other ields e6cept 5irst"ame must now be entered appropriately.

3hapter 9 Linking to Databases

()(

/ere the address elements are associated with the corresponding elements rom the @uery o the database success ully trans erred by the 4ail 4erge 7i0ard. +gain the irst record in the @uery is used or the pre*iew. The database settings are essentially ended with .tep 4. /ere) it is Rust a matter o choosing which ield the gender o the recipient should be ta,en rom. This ield has already been named) so that only the ield content or a emale recipient still needs to be speci ied. Three di erent salutations are to be produced. +ll records with a =w= start with Dear ;sT) all those with =m= with Dear ;rT ? there is no gender gi*en) Dear &ir/;adam is selected.

()8

Base Handbook

3hapter 9 Linking to Databases

()

"ormally the document is initially a rough s,etch which can be urther edited in 7riter. This can be done in .tep C.

#p to now all the documents ha*e been identical e6cept or the di erent content o the ields read rom the database. This can be changed in .tep E.

()!

Base Handbook

The ?tarting document is the document in which the field properties and the linkage to the database are stored. ?n the bac,ground meanwhile) you can see the original document with the contents o the irst record that is to be con*erted into the orm letter. This is called the 4ail 4erge document. :nly when one o the options is actually carried out &in the abo*e e6ample to sa*e the starting document( does the 4ail 4erge 7i0ard terminate.

+abel printing
Files 5 9ew 5 +abels launches the %abel $rinting 7i0ard. ?t opens a dialog) which includes all @uestions o ormating and content or labels) be ore the labels themsel*es are produced. The settings in this dialog are sa*ed in the personal settings or the user.

3hapter 9 Linking to Databases

()"

The basic settings or the content are in the Labels tab. ? or %abel te6t you chec, the +ddress bo6) all the labels will ha*e the same content) ta,en rom the %ibre: ice settings or the user o the program. +s an e6ample we will again use the >ddresses database. +lthough the ne6t selection ield is headed *ables) $ables and (ueries are both listed here) Rust as in the data source browser. The arrow buttons are used to insert indi*idual database ields into the editor. The name or the database ield &urname is set here to L>ddresses.;ail;ergeAuer0.(.&urname-. The se@uence is thus Ldatabase.*able.(.database field-. You can wor, with the ,eyboard in the editor. .o or e6ample) it is possible to insert a line brea, at the beginning) so that the labels will not be printed directly on the top edge but the content can be printed as completely and clearly *isible. The ormat can be selected in the tab Labels. /ere many label brands are incorporated so that most other settings in the tab 'ormat are not necessary.
?n *ersions 3.4.6 to 3.B.2) due to a change in the basic settings in the label wi0ard) display errors occurred when the labels were the same width as the page width. #nder these conditions) the last label simply slides down one line. ?n *ersion 3.B.3 page settings were added in the 'ormat tab.

9ote

The 'ormat tab allows you to set the label si0e accurately. The settings are only signi icant when the ma,e and type o the labels is not ,nown. ?t is noteworthy that) to print labels E.00 cm wide) you need a page width a little bigger than 3HE.00 cm Y 21.00 cm. :nly then will three labels be printed in a row on the page.

()#

Base Handbook

#nder the Options tab you can speci y whether only a single label or a whole page o labels will be produced. The page will then be illed with data rom successi*e records o the database) beginning with the irst record. ? there are more records than will it on the page) the ne6t page will automatically be illed with the ne6t set o records. The &0nchroni/e contents chec,bo6 lin,s all the labels together so that subse@uent changes in layout o any label will be applied to all the others. To trans er the edited content) Rust use the included button labelled &0nchroni/e) which appears during label production i you ha*e selected this chec,bo6. 5inally the 9ew #ocument button is used to create a document containing the selected ields. 7hen you initiate the printing process) the ollowing @uestion appears'

Choose Ces to ill the address database ields with the corresponding content.

3hapter 9 Linking to Databases

()9

The source o the data or the label printing is not ound automaticallyP only the database is preG selected. The actual @uery must be speci ied by the user) because in this case we are not dealing with a table. 7hen the @uery is selected and the corresponding records chosen &in this case >ll() the printing can begin. ?t is ad*isable) especially or the irst tests) to choose Output to a 'ile) which will sa*e the labels as a document. The option to sa*e in se*eral documents is not appropriate or label printing but rather or letters to di erent recipients which can then be wor,ed on subse@uently.

#irect creation of mail merge and label documents


?nstead o using the 7i0ard) you can o course produce mail merge and label documents directly.

-ail merge using the mouse


4ail merge ields can be ta,en rom the database browser using the mouse'

())

Base Handbook

.elect the table header with the le t mouse button. /old the button down and drag the cursor through the te6t document. The cursor changes its shape to an insert symbol. The 4ail4erge ield is inserted into the te6t document) here shown in the complete description which is made *isible using 8iew 5 Field names.

Creating form letters by selecting fields


4ail merge ields can be inserted using Insert 5 Fields 5 4ther 5 #atabase.

/ere all tables and @ueries in the selected database are a*ailable. #sing the = .nsert= button) the *arious ields can be inserted one a ter another directly into the te6t at the current cursor position. ? you want to create a salutation) which is usual in orm letters) you can use a hidden paragraph or hidden te6t' Insert 5 Fields 5 4ther 5 Functions 5 3idden paragraph. 5or both *ariants ta,e care that the condition you ormulate will not be ul illed) since you want the paragraph to be *isible. 5or the ormula Dear ;rs L&urname-I to appear only when the person is emale) a su icient condition is' 2A''/essesHM)%&*e/BeO=e/JH+e('e/6 RN "C" "ow the only remaining problem is that there may be no surname. #nder these circumstances) WDear &ir/;adamIW should appear so this is the condition you must insert. The o*erall condition is' 2A''/essesHM)%&Me/Be$=e/JH+e('e/6 RN "S" OR NOT 2A''/essesHM)%&Me/Be$=e/JH =/()*e6 That e6cludes the possibility o this paragraph appearing when the person is not emale or there is no entered surname. ?n the same way you can create entries or the masculine gender and or missing entries or the two remaining types o salutation.

3hapter 9 Linking to Databases

(),

"aturally you can create a salutation in the address ield in e6actly the same way) where*er the gender is speci ied. 5urther in ormation is gi*en in the %ibre: ice /elp under Hidden *e1t and 3onditional *e1t. : course it would be still simpler i someone who understands databases were to put the whole salutation right into the @uery. This can be done using a correlated sub@uery &see the chapter on Dueries in this /andboo,(. $articularly interesting or labels is the ield type "e6t record. ? this ield type is chosen at the end o a label) the ne6t label will be illed with data rom the ollowing record. Typical labels or se@uential label printing loo, li,e the ollowing igure when you use 8iew 5 Field names to ma,e the corresponding ield designations *isible'

'igure "): 'ield selection for labels with se@uential content

B/ternal forms
? simple orm properties a*ailable in %ibre: ice are to be used in other program modules such as 7riter and Calc) you only need to display the orm design toolbar) using 8iew 5 $oolbars 5 Form design) then open the 'orm navigator. You can build a orm or) as described in the 5orms chapter) create a orm ield. The Data tab o the 5orm $roperties dialog loo,s a little di erent rom the one you see when orms are built directly in an :29 database ile'

'igure ",: 'orm with an e1ternal data source

'igure #7: 'orm with an internal data source. The Data source must be selected separately when using an e6ternal orm. #se the button to the right o the data source listbo6 to open the ile browser. +ny :29 ile can be selected. ?n addition) the ield or the data source contains a lin,) beginning with ile'///. ? instead you loo, in the listbo6 contents) you will see databases already registered in %ibre: ice under their registered names. The orms are created in e6actly the same way as in 9ase itsel .

(,7

Base Handbook

Advantages of e/ternal forms 9ase need not be opened irst in order to wor, with the database. There ore you do not need an e6tra open window in the bac,ground. ?n a database that is already complete) e6isting database users can subse@uently be sent the impro*ed orm without problems. They can continue to use the database during the de*elopment o urther orms) and do not need to copy complicated e6ternal orms rom one database into another. 5orms or a database can be *aried to suit the user. #sers who do not ha*e the authority to correct data or ma,e new entries can be sent a current data set by other users) and simply replace their H.odb ile to ha*e an upGtoGdate *iew. This could) or e6ample) be use ul or a database or an association where all committee members get the database but only one person can edit the dataP the others can still *iew the addresses or their respecti*e departments. #isadvantages of e/ternal forms #sers must always install orms and 9ase with the same directory structure. That is the only way that access to the database can be ree rom errors. +s the lin,s are stored relati*e to the orm) it is su icient to store the database and its orms in a common directory. :nly orms can be created e6ternally) not @ueries or reports. + simple glance at a @uery there ore must go through a orm. + report on the other hand re@uires the opening o the database. +lternati*ely it might be possible to create it) at least partially) using mail merge.

#atabase use in Calc


2ata can be used in Calc or calculation purposes. 5or this purpose it is irst necessary to ma,e the data accessible in a Calc wor,sheet.

Bntering data into Calc


There are *arious ways o inserting data into Calc. .elect a table with the le t mouse button and drag it into a Calc wor,sheet. The cursor sets the le t upper corner o the table. The table is created complete with ield names. The data source browser in this case does not o er the options o Data into *e1t or Data into 'ields. #ata dragged into Calc in this way shows the following propertiesG "ot only the data are imported) but the ield properties too are read and acted on during the import. 5ields such as house numbers) which were declared as te6t ields) are ormatted as te6t a ter insertion into Calc. The import becomes a Calc range) which by de ault is assigned the name ?mport1. The data can later be accessed using this range. #ata 5 )efresh range allows the range) where appropriate) to be supplied with new data rom the database.

3hapter 9 Linking to Databases

(,(

The imported data is not ormatted e6cept as the properties o the database ields re@uire. You can also use the conte6t menu o a table to ma,e a copy o the data. ?n this case) howe*er) there is no import but merely a copy. The properties o the data ields are not read with them but are determined by Calc. ?n addition the ield names are ormatted as table headers.

(,8

Base Handbook

You see the di erence especially in database ields that are ormatted as te6t. :n import) Calc turns these into te6t ields and precedes numbers) which would otherwise be interpreted as such) with a single @uote (AEGT). These numbers can then no longer be used in calculations. ? you e6port them again) the single @uote is remo*ed) so that the data remain as they were.

B/porting data from Calc into a database


.elect the data in the Calc wor,sheet. /old the le t mouse button down and drag the data that you want to turn into a database into the table area o the database browser.

3hapter 9 Linking to Databases

(,

The cursor changes its appearance) showing that something can be inserted. The 3op0 *able dialog appears. ?n the abo*e case a new table is created. The table name is W"amesW. Definition and Data are to be trans erred. The irst line contains the column headers.

+t this point you can create a new additional ield or a primary ,ey. The name o this database ield must not be one that already e6ists as a column header in the Calc sheet. :therwise you get the error message' $he following fields are already set as primary keyG I# #n ortunately this message does not describe the problem @uite correctly. ? you want an e6isting ield to be used as the ,ey) do not chec, the 3reate primar0 ke0 bo6. ?n such cases the primary ,ey is set using the third dialog in the 7i0ard.

(,!

Base Handbook

The appropriate ields are selected. The ormatting o the columns needs to be chec,ed) especially or numeric ields. :ther ields should also be chec,ed or si0e. ?t Rust so happens that the test table contains only irst names with a ma6imum length o 10 characters) so that it can become a ield o type Barchar with a length o 10 characters.

/ere the ?2 ield) which is to be the primary ,ey) is ormatted. The primary ,ey must be set by using the conte6t menu o its ield name) in cases where it has not been created by the 7i0ard in the 3op0 *able dialog as an additional ield. + ter you clic, the 'inish button) the table is created. The new primary ,ey is not an >uto-Balue ,ey. To create such a ,ey) you must open the database or editing. There you can carry out urther ormatting o the table.

3hapter 9 Linking to Databases

(,"

Converting data from one database to another


?n the e6plorer o the data source browser) tables can be copied rom one database to another by selecting the source table with the le t mouse button) holding the button down) and dragging it into the target database in the table container. This causes the dialog or copying tables to be displayed. ?n this way) or e6ample) readGonly databases &data sources such as address boo,s rom an email program or a spreadsheet table( can be used as a basis or a database in which the data become editable. +lso data can be directly copied when changing to another database program & or e6ample changing rom $ostgre.D% to 4y.D%(. ? you wish the new database to ha*e di erent relationships rom the original one) you can arrange this by using appropriate @ueries. Those who are not su iciently e6pert can instead use Calc. -ust drag the data into a spreadsheet and prepare them or import into the target database using the acilities that Calc pro*ides. 5or the cleanest possible import into a new database) the tables should be prepared in ad*ance. This allows problems o ormatting and those in*ol*ing the creation o primary ,eys to be recogni0ed well in ad*ance.

(,#

Base Handbook

3hapter ) Database tasks

6eneral remarks on database tasks


This chapter describes some solutions or problems that arise or many datsbase users.

#ata filtering
2ata iltering using the !#? is described in the chapter on data entry into tables. /ere we describe a solution to a problem which many users ha*e raised' how to use listbo6es to search or the content o ields in tables) which then appear iltered in the underlying orm section and can be edited. The basis or this iltering is an editable @uery &see the chapter on @ueries( and an additional table) in which the data to be iltered are stored. The @uery shows rom its underlying table only the records that correspond to the ilter *alues. ? no ilter *alue is gi*en) the @uery shows all records. The ollowing e6ample starts rom a Me'%)Ex)*<&e table that includes) among others) the ollowing ields' ID &primary ,ey() T%t&e) C)teB-/J. The ield types are INTE+ER) VARCHAR) and VARCHAR respecti*ely. 5irst we re@uire a "%&te/Ex)*<&e table. This table contains a primary ,ey and 2 ilter ields &o course you can ha*e more i you want(' "ID" &primary ,ey() "%&te/_E) "%&te/_8. +s the ields o the Me'%)Ex)*<&e table) which is to be iltered) are o the type VARCHAR) the ields "%&te/_E and "%&te/_8 are also o this type. ID can be the smallest numeric type) TINYINT because the Filter table will ne*er contain more than one record. You can also ilter ields that occur in the -ediaB/ample table only as oreign ,eys. ?n that case) you must gi*e the corresponding ields in the FilterB/ample table the type appropriate or the oreign ,eys) usually I9$B6B). The ollowing @uery is certainly editable' ')'&( I FROM "Media'xample" +ll records rom the Me'%)Ex)*<&e table are displayed) including the primary ,ey. ')'&( I FROM "Media'xample" @1'R' "(itle" E +F-A))* * "Filter_C" FROM "Filter'xample" 4" "(itle" 4 ')'&(

? the ield "%&te/_E is not NULL) those records are displayed or which the T%t&e is the same as "%&te/_E. ? the ield "%&te/_E is NULL" the *alue o the T%t&e ield is used instead. +s T%t&e is the same as "T%t&e") all records are displayed. This assumption does not hold howe*er i the T%t&e ield o any record is empty &contains NULL). That means that those records will ne*er be displayed that ha*e no title entry. There ore we need to impro*e the @uery' ')'&( I " +F-A))* "(itle"" GG 4 A "(" FROM "Media'xample" @1'R' "(" E +F-A))* * ')'&( "Filter_C" FROM "Filter'xample" 4" "(" 4 I"NULL(ex</ess%-(, :)&=e) re@uires the ex</ess%-( has the same ield type as the :)&=e. ? the ex</ess%-( has the ield type VARCHAR) use two single @uotes AA as the *alue.

$ip

? it has DATE as its ield type) enter a date as the *alue that is not contained
in the ield o the table to be iltered. #se this ormat' 3D AYYYY>MM>DDA5.

? it is any o the numerical ield types) use the NUMERIC ield type or the
*alue. Fnter a number that does not appear in the ield o the table to be iltered.

(,)

Base Handbook

This *ariant will lead to the desired goal. ?nstead o iltering T%t&e directly) a ield is iltered which carries the alias T. This ield has no content either but it is not NULL. ?n the conditions only the ield T is considered. +ll records are there ore displayed e*en i T%t&e is NULL. #n ortunately you cannot do this using the !#?. This command is a*ailable only directly with .D%. To ma,e it editable in the !#?) urther modi ication is re@uired' ')'&( "Media'xample".I " +F-A))* "Media'xample"."(itle"" GG 4 A "(" FROM "Media'xample" @1'R' "(" E +F-A))* * ')'&( "Filter_C" FROM "Filter'xample" 4" "(" 4 ? the relationship o the table to the ields is now set up) the @uery becomes editable in the !#?. +s a test) you can put a title into ""%&te/"H""%&te/_E". +s ""%&te/"H"ID" set the *alue A0A. The record is sa*ed and the iltering can be comprehended. ? ""%&te/"H""%&te/_E" is emptied) the !#? treats that as NULL. + new test yields a display o all the media. ?n any case) be ore a orm is created and tested) Rust one record with a primary ,ey should be entered into the "%&te/ table. ?t must be only one record) since subG@ueries as shown abo*e can only transmit one *alue. The @uery can now be enlarged to ilter two ields' ')'&( "Media'xample".I " +F-A))* "Media'xample"."(itle"" GG 4 A "("" +F-A))* "Media'xample"."&ate$ory"" GG 4 A "#" FROM "Media'xample" @1'R' "(" E +F-A))* * ')'&( "Filter_C" FROM "Filter'xample" 4" "(" 4 A-, "#" E +F-A))* * ')'&( "Filter_D" FROM "Filter'xample" 4" "#" 4 This concludes the creation o the editable @uery. "ow or the basic @uery or the two listbo6es' ')'&( ,+ (+-&( "(itle"" "(itle" FROM "Media'xample" OR,'R !/ "(itle" A & The listbo6 should show the T%t&e and then also transmit that T%t&e to the "%&te/_E ield in the "%&te/ table that underlies the orm. +lso no duplicate *alues should be shown &ADI TINCTA co%ditio%( . +nd the whole thing should o course be sorted into the correct order. + corresponding @uery is then created or the C)teB-/J ield) which is to write its data into the "%&te/_8 ield in the "%&te/ table. ? one o these ields contains a oreign ,ey) the @uery is adapted so that the oreign ,ey is passed to the underlying "%&te/ table. The orm consists o two parts. 5orm 1 is the orm based on the "%&te/ table. 5orm 2 is the orm based on the @uery. 5orm 1 has no navigation bar and the cycle is set to Current record. ?n addition) the Allow additions property is set to 9o. The irst and only record or this orm already e6ists. 5orm 1 contains two listbo6es with appropriate labels. %istbo6 1 returns *alues or "%&te/_E and is lin,ed to the @uery or the T%t&e ield. %istbo6 2 returns *alues or "%&te/_8 and relates to the @uery or the C)teB-/J ield. 5orm 2 contains a table control ield) in which all ields rom the @uery can be listed e6cept or the ields T und K. The orm would still wor, i these ields were presentP they are omitted to a*oid a con using duplication o ield contents. ?n addition orm 2 contains a button) lin,ed to the :pdate form unction. +n additional na*igation bar can be built in to pre*ent screen lic,er e*ery time the orm changes) due to the na*igation bar being present in one orm and not in the other. :nce the orm is inished) the test phase begins. 7hen a listbo6 is changed) the button on orm 2 is used to store this *alue and update 5orm 2. This now relates to the *alue which the listbo6 pro*ides. The iltering can be made retrospecti*e by choosing an empty ield in the listbo6.

3hapter ) Database tasks

(,,

?earching for data


The main di erence between searching or data and iltering data is in the @uery techni@ue. The aim is to deli*er) in response to ree language search terms) a resulting list o records that may only partially contain these actual terms. 5irst the similar approaches to the table and orm are described. The table or the search content may be the same one that already contains the ilter *alues. The "%&te/ table is simply e6panded to include a ield named e)/7.te/*. .o) i re@uired) the same table can be accessed and) using the orms) simultaneously iltered and searched. e)/7.te/* has the ield type VARCHAR. The orm is built Rust as or iltering. ?nstead o a listbo6) we need a te6t entry ield or the search term) and also perhaps a label ield with the title .earch. The ield or the search term can stand alone in the orm or together with the ields or iltering) i both unctions are desired. The di erence between iltering and searching lies in the @uery techni@ue. 7hile iltering uses a term that already occurs in the underlying table) searching uses arbitrary entries. &+ ter all) the listbo6 is constructed rom the table content.( ')'&( I FROM "Media'xample" @1'R' "(itle" E * FROM "Filter'xample" 4 ')'&( " earchterm"

This @uery normally leads to an empty result list or these reasons' <( 7hen entering search terms ) people seldom ,now completely and accurately what the title is. There ore the correct title does not get displayed. To ind the boo, W$er +nhalter through the !ala6yW it should be su icient to put W+nhalterW into the .earch ield or e*en Rust W+nhW. >( ? the ield I.earchtermJ is empty) only records are displayed in which there is no title. The ield I.earchtermJ is empty) the T%t&e ield must be empty also. This only happens in one o two possibilities' the item does not ha*e a title) or someone did not enter its title. The last condition can be remo*ed i the iltering condition is' ')'&( I FROM "Media'xample" @1'R' "(itle" E +F-A))* * ')'&( " earchterm" FROM "Filter'xample" 4" "(itle" 4 7ith this re inement o the iltering &what happens i the title is NULL;( we get a result more in line with e6pectations. 9ut the irst condition is still not ul illed. .earching should wor, well when only ragmentary ,nowledge is a*ailable. The @uery techni@ue must there ore use the LIKE condition' ')'&( I FROM "Media'xample" @1'R' "(itle" )+#' * " earchterm" 77GQG FROM "Filter'xample" 4 or better still' ')'&( GQG 77

')'&( I FROM "Media'xample" @1'R' "(itle" )+#' +F-A))* * 77 " earchterm" 77GQG FROM "Filter'xample" 4" "(itle" 4

')'&( GQG

LIKE) coupled with ?) means that all records are displayed which ha*e the search term anywhere within them. ? is a wildcard or any number o characters be ore or a ter the search term. Various proRects still remain a ter this *ersion o the @uery has been built'

T T T T

?t is common to use lower case letters or search terms. .o how do ? get a result i ? type WanhalterW instead o W+nhalterW; 7hat other con*entions in writing need to be considered; 7hat about ields that are not ormatted as te6t ields; Can you search or dates or numbers with the same search ield; +nd what i ) as in the case o the ilter) you want to pre*ent NULL *alues in the ield rom causing all the records to being displayed;

877

Base Handbook

The ollowing *ariant co*ers one or two o these possibilities' ')'&( I FROM "Media'xample" @1'R' )O@'R*"(itle"4 )+#' +F-A))* * ')'&( GQG 77 )O@'R*" earchterm"4 77GQG FROM "Filter'xample" 4" )O@'R*"(itle"4 4 The condition changes the search term and the ield content to lower case. This also allows whole sentences to be compared. ')'&( I FROM "Media'xample" @1'R' )O@'R*"(itle"4 )+#' +F-A))* * ')'&( GQG 77 )O@'R*" earchterm"4 77GQG FROM "Filter'xample" 4" )O@'R*"(itle"4 4 OR )O@'R*"&ate$ory"4 )+#' * ')'&( GQG 77 )O@'R*" earchterm"4 77GQG FROM "Filter'xample" 4 The I"NULL unction must occur only once) so that when the e)/7.te/* is NULL) LO!ER("T%t&e") LIKE LO!ER("T%t&e") is @ueried. +nd as the title should be a ield that cannot be NULL) in such cases all records are displayed. : course) or multiple ield searches) this code becomes correspondingly longer. ?n such cases it is better to use a macro) to allow the code to co*er all the ields in one go. 9ut does the code still wor, with ields that are not te6t; +lthough the %?QF condition is really tailored to te6t) it also wor,s or numbers) dates) and times without needing any alterations. .o in act te6t con*ersion need not ta,e place. /owe*er) a time ield that is a mi6ture o te6t and numbers cannot interact with the search results A unless the @uery is broadened) so that a single search term is subdi*ided across all the spaces between the te6t and numbers. This) howe*er) will signi icantly bloat the @uery.

Code snippets
These code snippets come rom @ueries to mailing lists. $articular problems arise that might perhaps be use ul as solutions or your own database e6periments.

6etting someone2s current age


+ @uery needs to calculate a person=s actual age rom a birth date. .ee also the unctions in the appendi6 to this 9ase /andboo,. ')'&( ,A(',+FF*GyyG""!irthdate""&AR,A('*44 A "A$e" FROM ".erso%" This @uery gi*es the age as a di erence in years. 9ut) the age o a child born on 31 2ecember 31 2011 would be gi*en as 1 year on 1 -anuary 2012. .o we also need to consider the position o the day within the year. This is accessible using the ADAYO"YEAR()A unction. +nother unction will carry out the comparison. ')'&( &A '@1'* ,A/OF/'AR*"!irthdate"4 = ,A/OF/'AR*&AR,A('*44 " ,A(',+FF *GyyG""!irthdate""&AR,A('*44FC" ,A(',+FF *GyyG""!irthdate""&AR,A('*444 A "A$e" FROM ".erso%" "ow we get the correct current age in years. CA E!HEN can also be used to ma,e the te6t B%/t.')J t-')J appear in another ield) i DAYO"YEAR("B%/t.')te") N DAYO"YEAR(CURDATE()). + subtle obRection might now arise' W7hat about leap years;W. 5or persons born a ter 2< 5ebruary) there will be an error o one day. "ot a serious problem in e*eryday use) but should we not stri*e or accuracy;

3hapter ) Database tasks

87(

&A '@1'- * *MO-(1*"!irthdate"4 = MO-(1*&AR,A('*444 OR **MO-(1*"!irthdate"4 E MO-(1*&AR,A('*444 A-, *,A/*"!irthdate"4 = ,A/*&AR,A('*4444 " ,A(',+FF*GyyG""!irthdate""&AR,A('*44FC" ,A(',+FF*GyyG""!irthdate""&AR,A('*444 The code abo*e achie*es this goal. +s long as the month o the birth date is greater than the current month) the year di erence unction will subtract one year. F@ually one year will be subtracted when the two months are the same) but the day o the month or the birth date is greater than the day in the current date. #n ortunately this ormula is not comprehensible to the !#?. :nly 2#irect ?(+QCommand2 will handle this @uery success ully and that would pre*ent our @uery rom being edited. 9ut the @uery needs to be editable) so here is how to tric, the !#?' &A ' @1'- MO-(1*"!irthdate"4 = MO-(1*&AR,A('*44 (1'- ,A(',+FF*GyyG""!irthdate""&AR,A('*44FC @1'- *MO-(1*"!irthdate"4 E MO-(1*&AR,A('*44 A-, ,A/*"!irthdate"4 = ,A/*&AR,A('*444 (1'- ,A(',+FF*GyyG""!irthdate""&AR,A('*44FC ') ' ,A(',+FF*GyyG""!irthdate""&AR,A('*44 '-, 7ith this ormulation) the !#? no longer reacts with an error message. The age is now gi*en accurately e*en in leap years and the @uery still remains editable.

6etting a running balance by categories


?nstead o using a household boo,) a database on a $C can simpli y the tiresome business o adding up e6penses or ood) clothing) transport and so on. 7e want most o these details to be immediately *isible in the database) so our e6ample assumes that income and e6penditure will be stored as signed *alues in one ield called +mount. ?n principle) the whole thing can be e6panded to co*er separate ields and a rele*ant summation or each. ')'&( "+,"" "Amou%t"" * ')'&( AM* "Amou%t" 4 FROM "&ash" @1'R' "+," ;E "a"."+," 4 A "!ala%ce" FROM "&ash" A "a" OR,'R !/ "+," A & This @uery causes or each new record a direct calculation o the current account balance. +t the same time the @uery remains editable because the W9alanceW ield is created through a correlating subG@uery. The @uery depends on the automatically created primary ,ey W?2W to calculate the state o the account. /owe*er balances are usually calculated on a daily basis. .o we need a date @uery. ')'&( "+,"" ",ate"" "Amou%t"" * ')'&( AM* "Amou%t" 4 FROM "&ash" @1'R' ",ate" ;E "a".",ate" 4 A "!ala%ce" FROM "&ash" A "a" OR,'R !/ ",ate"" "+," A & The e6penditure now appears sorted and summed by date. There still remains the @uestion o the category) since we want corresponding balances or the indi*idual categories o e6penditure. ')'&( "+,"" ",ate"" "Amou%t"" "Acct_+,"" * ')'&( "Acct" FROM "Acct" @1'R' "+," E "a"."Acct_+," 4 A "Acct_%ame"" * ')'&( AM* "Amou%t" 4 FROM "&ash" @1'R' ",ate" ;E "a".",ate" A-, "Acct_+," E "a"."Acct_+," 4 A "!ala%ce"" * ')'&( AM* "Amou%t" 4 FROM "&ash" @1'R' ",ate" ;E "a".",ate" 4 A "(otal_bala%ce" FROM "&ash" A "a" OR,'R !/ ",ate"" "+," A &

878

Base Handbook

This creates an editable @uery in which) in addition to the entry ields &2ate) +mount) +cctL?2() the account name) the rele*ant balance) and the total balance appear together. +s the correlating sub@ueries are partially based on pre*ious entries &W2ateW ZY WaW.W2ateW( only new entries will go through smoothly. +lterations to a pre*ious record are initially detectable only in that record. The @uery must be updated i later calculations dependent on it are to be carried out.

+ine numbering
+utomatically incrementing ields are ine. /owe*er) they do not tell you de initely how many records are present in the database or are actually a*ailable to be @ueried. 1ecords are o ten deleted and many users try in *ain to determine which numbers are no longer present in order to ma,e the running number match up. ')'&( "+,"" * ')'&( &OA-(* "+," 4 FROM "(able" @1'R' "+," ;E "a"."+," 4 A "-r." FROM "(able" A "a" The ?2 ield is read) and the second ield is determined by a correlating subG@uery) which see,s to determine how many ield *alues in ?2 are smaller than or e@ual to the current ield *alue. 5rom this a running line number is created. Fach record to which you want to apply this @uery contains ields. To apply this @uery to the records) you must irst add these ields to the @uery. You can place them in whate*er order you desire in the ELECT clause. ? you ha*e the records in a orm) you need to modi y the orm so that the data or the orm comes rom this @uery. 5or e6ample the record contains ield1) ield2) and ield3. The complete @uery would be' ')'&( "+,"" "<ieldC"" "<ieldD"" "<ieldR"" * ')'&( &OA-(* "+," 4 FROM "(able" @1'R' "+," ;E "a"."+," 4 A "-r." FROM "(able" A "a" + numbering or a corresponding grouping is also possible' ')'&( "+,"" "C)&7=&)t%-(", * ')'&( &OA-(* "+," 4 FROM "(able" @1'R' "+," ;E "a"."+," A-, "&alculatio%" E "a"."&alculatio%" 4 A "-r." FROM "(able" A "a" ORDER BY "ID" A C, "N/H" A C /ere one table contains di erent calculated numbers. &WCalculationW(. 5or each calculated number) "N/H" is separately e6pressed in ascending order a ter sorting on the ?2 ield. This produces a numbering rom 1 upwards. ? the actual sort order within the @uery is to agree with the line numbers) an appropriate type o sorting must be mapped out. 5or this purpose the sort ield must ha*e a uni@ue *alue in all records. :therwise two place numbers will ha*e the same *alue. This can actually be use ul i ) or e6ample) the place order in a competition is to be depicted) since identical results will then lead to a Roint position. ?n order or the place order to be e6pressed in such a way that) in case o Roint positions) the ne6t *alue is omitted) the @uery needs to be be constructed somewhat di erently' ')'&( "+,"" * ')'&( &OA-(* "+," 4 H C FROM "(able" @1'R' "(ime" ; "a"."(ime" 4 A ".lace" FROM "(able" A "a" +ll entries are e*aluated or which the WTimeW ield has a smaller *alue. That co*ers all athletes who reached the winning post be ore the current athlete. To this *alue is added the number 1. This determines the place o the current athlete. ? the time is identical with that o another athlete) they are placed Rointly. This ma,es possible place orders such as 1st $lace) 2nd $lace) 2nd $lace) 4. $lace. ?t would be more problematic) i line numbers were re@uired as well as a place order. That might be use ul i se*eral records needed to be combined in one line.
')'&( "+,"" * ')'&( &OA-(* "+," 4 H C FROM "(able" @1'R' "(ime" ; "a"."(ime" 4 A ".lace"" &A ' @1'* ')'&( &OA-(* "+," 4 H C FROM "(able" @1'R' "(ime" E "a"."(ime" 4 E C
3hapter ) Database tasks 87

(1'- * ')'&( &OA-(* "+," 4 H C FROM "(able" @1'R' "(ime" ; "a"."(ime" 4 ') ' * ')'&( * ')'&( &OA-(* "+," 4 H C FROM "(able" @1'R' "(ime" ; "a"."(ime" 4 H &OA-(* "+," 4 FROM "(able" @1'R' "(ime" E "a"."(ime" "+," ; "a"."+," '-, A ")i%e-umber" FROM "(able" A "a"

The second column still gi*es the place order. The third column chec,s irst i only one person crossed the line with this time. ? so) the place order is con*erted directly into a line number. :therwise a urther *alue is added to the place order. 5or the same time &"T%*e" N ")"H"T%*e"( at least 1 is added) i there is a urther person with the primary ,ey ?2) whose primary ,ey is smaller than the primary ,ey in the current record &"ID" , ")"H"ID"(. This @uery there ore yields identical *alues or the place order so long as no second person with the same time e6ists. ? a second person with the same time does e6ist) the ?2 determines which person has the lesser line number. ?ncidentally) this sorting by line number can ser*e whate*er purpose the users o the database want. 5or e6ample) i a series o records are sorted by name) records with the same name are not sorted randomly but according to their primary ,ey) which is o course uni@ue. ?n this way too) numbering can lead to a sorting o records. %ine numbering is also a good prelude to the combining o indi*idual records into a single record. ? a lineGnumbering @uery is created as a *iew) a urther @uery can be applied to it without creating any problem. +s a simple e6ample here once more is the irst numbering @uery with one e6tra ield' ')'&( "+,"" "-ame"" * ')'&( &OA-(* "+," 4 FROM "(able" @1'R' "+," ;E "a"."+," 4 A "-r." FROM "(able" A "a" This @uery is turned into the *iew =Biew(S. The @uery can be used) or e6ample) to put the irst three names together in one line' ')'&( "-ame" A "-ame_C"" * ')'&( "-ame" FROM "0iewC" @1'R' "-r." E D 4 A "-ame_D"" * ')'&( "-ame" FROM "0iewC" @1'R' "-r." E R 4 A "-ame_R" FROM "0iewC" @1'R' "-r." E C ?n this way se*eral records can be con*erted into adRacent ields. This numbering simply runs rom the irst to the last record. ? all these indi*iduals are to be assigned the same surname) this can be carried out as ollows' ')'&( "+,"" "-ame"" " ur%ame"" * ')'&( &OA-(* "+," 4 FROM "(able" @1'R' "+," ;E "a"."+," A-, " ur%ame" E "a"." ur%ame"4 A "-r." FROM "(able" A "a" "ow that the *iew has been created) the amily can be assembled. ')'&( " ur%ame"" "-ame" A "-ame_C"" * ')'&( "-ame" FROM "0iewC" @1'R' "-r." E D A-, " ur%ame" E "a"." ur%ame"4 A "-ame_D"" * ')'&( "-ame" FROM "0iewC" @1'R' "-r." E R A-, " ur%ame" E "a"." ur%ame"4 A "-ame_R" FROM "0iewC" A "a" @1'R' "-r." E C ?n this way) in an address boo,) all members o one amily &W.urnameW( can be collected together so that each address need be considered only once when sending a letter) but e*eryone who should recei*e the letter is listed. 7e need to be care ul here) as we do not want an endlessly looping unction. The @uery in the abo*e e6ample limits the parallel records that are to be con*erted into ields to 3. This limit was chosen deliberately. "o urther names will appear e*en i the *alue o J?r.J is greater than 3. ?n a ew cases such a limit is clearly understandable. 5or e6ample) i we are creating a calendar) the lines might represent the wee,s o the year and the columns the wee,days. +s in the original calendar only the date determines the ield content) line numbering is used to number the days o each wee, continuously and then the wee,s in the year become the records. This does re@uire that the table contains a date ield with continuous dates and a ield or the e*ents. +lso the earliest
87! Base Handbook

date will always create an I"r.J Y 1. .o) i you want the calendar to begin on 4onday) the earliest date must be on 4onday. Column 1 is then 4onday) column 2 Tuesday and so on. The sub@uery then ends at J?r.J Q 9. ?n this way all se*en days o the wee, can be shown alongside each other and a corresponding calendar *iew created.

6etting a line break through a ;uery


.ometimes it is use ul to assemble se*eral ields using a @uery and separate them by line brea,s) or e6ample when reading a complete address into a report. The line brea, within the @uery is represented by AC.)/(EG)A. F6ample' ')'&( "First%ame"77G G77" ur%ame"77&har*CR477"Road"77&har*CR477"(ow%" FROM "(able" This yields' First%ame ur%ame Road (ow% .uch a @uery) with a line numbering up to 3) allows you to print address labels in three columns by creating a report. The numbering is necessary in this connection so that three addresses can be placed ne6t to one another in one record. That is the only way they will remain ne6t to each other when read into the report.

6rouping and summariPing


5or other databases) and or newer *ersions o /.D%29) the +/-=<_C-(7)t() command is a*ailable. ?t can be used to group indi*idual ields in a record into one ield. .o) or e6ample) it is possible to store irst names and surnames in one table) then to present the data in such a way that one ield shows the surnames as amily names while a second ield contains all the rele*ant irst names se@uentially) separated by commas. This e6ample is similar in many ways to line numbering. The grouping into a common ield is a ,ind o supplement to this. &urname
4Xller .chneider 4Xller .chneider 4Xller 4Xller

'irstname
Qarin !erd Fgon Vol,er 4oni,a 1ita

is con*erted by the @uery to' &urname


4Xller .chneider

'irstnames
Qarin) Fgon) 4oni,a) 1ita !erd) Vol,er

This procedure can) within limits) be e6pressed in /.D%29. The ollowing e6ample re ers to a table called "ame with the ields ?2) 5irstname and .urname. The ollowing @uery is irst run on the table and sa*ed as a *iew called ViewL!roup.

3hapter ) Database tasks

87"

')'&( " ur%ame"" "First%ame"" * ')'&( &OA-(* "+," 4 FROM "-ame" @1'R' "+," ;E "a"."+," A-, " ur%ame" E "a"." ur%ame" 4 A "8roup-r" FROM "-ame" A "a" You can read in the Dueries chapter how this @uery accesses the ield content in the same @uery line. ?t yields an ascending numbered se@uence) grouped by &urname. This numbering is necessary or the ollowing @uery) so that in the e6ample a ma6imum o B irst names is listed. ')'&( " ur%ame"" * ')'&( "First%ame" FROM "0iew_8roup" @1'R' " ur%ame" A-, "8roup-r" E C 4 77 +F-A))* * ')'&( G" G 77 "First%ame" FROM "0iew_8roup" E "a"." ur%ame" A-, "8roup-r" E D 4" GG 4 77 +F-A))* * ')'&( G" G 77 "First%ame" FROM "0iew_8roup" E "a"." ur%ame" A-, "8roup-r" E R 4" GG 4 77 +F-A))* * ')'&( G" G 77 "First%ame" FROM "0iew_8roup" E "a"." ur%ame" A-, "8roup-r" E N 4" GG 4 77 +F-A))* * ')'&( G" G 77 "First%ame" FROM "0iew_8roup" E "a"." ur%ame" A-, "8roup-r" E 2 4" GG 4 A "First%ames" FROM "0iew_8roup" A "a" E "a"." ur%ame" @1'R' " ur%ame" @1'R' " ur%ame" @1'R' " ur%ame" @1'R' " ur%ame"

#sing subG@ueries) the irst names o the group members are searched or one a ter another and combined. 5rom the second subG@uery onward you must ensure that ANULLA *alues do not set the whole combination to ANULLA. That is why a result o AA rather than ANULLA is shown.

87#

Base Handbook

3hapter , ;acros

6eneral remarks on macros


?n principle a database in 9ase can manage without macros. +t times) howe*er) they may become necessary or'

T T T

4ore e ecti*e pre*ention o input errors .impli ying certain processing tas,s &changing rom one orm to another) updating data a ter input into a orm) and so on( +llowing certain .D% commands to be called up more easily than with the separate .D% editor.

You must decide or yoursel how intensi*ely you wish to use macros in 9ase. 4acros can impro*e usability but are always associated with small reductions in the speed o the program) and sometimes with larger ones &when coded poorly(. ?t is always better to start o by ully utili0ing the possibilities o the database and the pro*isions or con iguring orms be ore trying to pro*ide additional unctionality with macros. 4acros should always be tested on larger databases to determine their e ect on per ormance. 4acros are created using $ools 5 -acros 5 4rganiPe macros 5 +ibre4ffice asic. + window appears which pro*ides access to all macros. 5or 9ase) the important area corresponds to the ilename o the 9ase ile.

The 9ew button in the %ibre: ice 9asic 4acros dialog opens the "ew 4odule dialog) which as,s or the module name &the older in which the macro will be iled(. The name can be altered later i desired. +s soon as this is gi*en) the macro editor appears. ?ts input area already contains the .tart and the Fnd or a subroutine'
R'M IIIII !A +& IIIII

ub Mai% '%d ub

87)

Base Handbook

? macros are to be usable) the ollowing steps are necessary'

T T

#nder $ools 5 4ptions 5 ?ecurity 5 -acro security the security le*el should be reduced to 4edium. ? necessary you can additionally use the Trusted sources tab to set the path to your own macro iles to pre*ent later @ueries about the acti*ation o macros. The database ile must be closed and then reopened a ter the creation o the irst macro module. %ines ha*e no line numbers and must end with a hard return. 5unctions) reser*ed e6pressions) and similar elements are not caseGsensiti*e. .o W.tringW is the same as W.T1?"!W or WstringW or any other combination o upper and lower case. Case should be used only to impro*e legibility. "ames or constants and enumerations) howe*er) are case sensiti*e the irst time that they are seen by the macro compiler) so it is best to always write those using the proper case. There is a basic di erence between subroutines &beginning with .#9( and unctions &beginning with 5#"CT?:"(. .ubroutines are program segments without return *alues. 5unctions return a *alue.

.ome basic principles or the use o 9asic code in %ibre: ice'

T T

5or urther details see Chapter 13) !etting .tarted with 4acros) in the %etting &tarted guide.
4acros in the $25 and :2T *ersions o this chapter are colored according to the rules o the %ibre: ice macro editor' Macro desi$%atio% Macro comme%t Macro operator Macro reserved expressio% Macro %umber Macro character stri%$

9ote

Improving usability
5or this irst category o macro use) we show *arious possibilities or impro*ing the usability o 9ase orms.

Automatic updating of forms


: ten something is altered in a orm and this alteration is re@uired to appear in a second orm on the same page. The ollowing code snippet calls the reload method on the second orm) causing it to re resh.
A! Apdate

5irst the macro is named. The de ault designation or a macro is UB. This may be written in upper or lower case. UB allows a subroutine to run without returning a *alue. 5urther down by contrast a unction is described) which does return a *alue. The macro has the name +pdate. You do not need to declare *ariables because %ibre: ice 9asic automatically creates *ariables when they are used. #n ortunately) i you misspell a *ariable) %ibre: ice 9asic silently creates a new *ariable without complaint. #se O<t%-( Ex<&%7%t To pre*ent %ibreo: ice 9asic rom automatically creating *ariablesP this is recommended by most programmers. There ore we usually start by declaring *ariables. +ll the *ariables declared here are obRects &not numbers or te6t() so we add A OBMECT to the end o the declaration. To remind us later o the

3hapter , ;acros

87,

type o the *ariables) we pre ace their names with an WoW. ?n principle) though) you can choose almost any *ariable names you li,e.
,+M o,oc A O!L'&( ,+M o,rawpa$e A O!L'&( ,+M oForm A O!L'&(

The orm lies in the currently acti*e document. The container) in which all orms are stored) is named '/)S<)Be. ?n the orm na*igator this is the topGle*el concept) to which all the orms are subsidiary. ?n this e6ample) the orm to be accessed is named 2isplay. 2isplay is the name *isible in the orm na*igator. .o) or e6ample) the irst orm by de ault is called 5orm1.
o,oc E this&ompo%e%t o,rawpa$e E o,oc.drawpa$e oForm E o,rawpa$e.<orms.$et!y-ame*",isplay"4

.ince the orm has now been made accessible and the point at which it can be accessed is sa*ed in the *ariable -"-/*) it is now reloaded &re reshed( with the /e&-)'() command.
'-, oForm.reload*4 A!

The subroutine begins with UB so it must end with END

UB.

This macro can now be selected to run when another orm is sa*ed. 5or e6ample) on a cash register &till() i the total number o items sold and their stoc, numbers &read by a barcode scanner( are entered into one orm) another orm in the same open window can show the names o all the items) and the total cost) as soon as the orm is sa*ed.

Filtering records
The ilter itsel can unction per ectly well in the orm described in Chapter <) 2atabase Tas,s. The *ariant shown below replaces the .a*e button and reads the listbo6es again) so that a chosen ilter rom one listbo6 can restrict the choices a*ailable in the other listbo6.
A! Filter ,+M o,oc A O!L'&( ,+M o,rawpa$e A O!L'&( ,+M oFormC A O!L'&( ,+M oFormD A O!L'&( ,+M oField)istC A O!L'&( ,+M oField)istD A O!L'&( o,oc E this&ompo%e%t o,rawpa$e E o,oc.drawpa$e

5irst the *ariables are de ined and set to access the set o orms. This set comprises the two orms W5ilterW and W2isplayW. The listbo6es are in the W5ilterW orm and ha*e the names W%istL1W and W%istL2W.
oFormC E o,rawpa$e.<orms.$et!y-ame*"Filter"4 oFormD E o,rawpa$e.<orms.$et!y-ame*",isplay"4 oField)istC E oFormC.$et!y-ame*")ist_C"4 oField)istD E oFormC.$et!y-ame*")ist_D"4

5irst the contents o the listbo6es are trans erred to the underlying orm using 7-**%t(). The trans er is necessary) because otherwise the change in a listbo6 will not be recogni0ed when sa*ing. The 7-**%t() instruction need only be applied to the listbo6 that has Rust been accessed. + ter that the record is sa*ed using =<')teR-S(). ?n principle) our ilter table contains only one record) which is written once at the beginning. This record is there ore o*erwritten continuously using an update command.

8(7

Base Handbook

oField)istC.commit*4 oField)istD.commit*4 oFormC.updateRow*4

The listbo6es are meant to in luence each other. 5or e6ample) i one listbo6 is used to restrict displayed media to C2s) the other listbo6 should not include all the writers o boo,s in its list o authors. + selection in the second listbo6 would then all too o ten result in an empty ilter. That is why the listbo6es must be read again. .trictly spea,ing) the /eC/es.() command only needs to be carried out on the listbo6 that has not been accessed. + ter this) orm2) which should display the iltered content) is read in again.
oField)istC.re<resh*4 oField)istD.re<resh*4 oFormD.reload*4 '-, A!

%istbo6es that are to be in luenced using this method can be supplied with content using *arious @ueries. The simplest *ariant is to ha*e the listbo6 ta,e its content rom the ilter results. Then a single ilter determines which data content will be urther iltered. ')'&( "Field_C" 77 G F G 77 "&ou%t" A ",isplay"" "Field_C" FROM * ')'&( &OA-(* "+," 4 A "&ou%t"" "Field_C" FROM "(able_Filter_result" 8ROA. !/ "Field_C" 4 OR,'R !/ "Field_C" The ield content and the number o hits is displayed. To get the number o hits) a subG@uery is used. This is necessary as otherwise only the number o hits) without urther in ormation rom the ield) will be shown in the listbo6. The macro creates listbo6es @uite @uic,ly by this actionP they are illed with only one *alue. ? a listbo6 is not "#%%) it is ta,en into account by the iltering. + ter acti*ation o the second listbo6) only the empty ields and one displayed *alue are a*ailable to both listbo6es. That may seem practical or a limited search. 9ut what i a library catalog shows clearly the classi ication or an item) but does not show uni@uely i this is a boo,) a C2 or a 2V2; ? the classi ication is chosen irst and the second listbo6 is then set to WC2W) it must be reset to "#%% in order to carry out a subse@uent search that includes boo,s. ?t would be more practical i the second listbo6 showed directly the *arious media types a*ailable) with the corresponding hit counts. To achie*e this aim) the ollowing @uery is constructed) which is no longer ed directly rom the ilter results. The number o hits must be obtained in a di erent way. ')'&( +F-A))* "Field_C" 77 G F G 77 "&ou%t"" Gempty F G 77 "&ou%t" 4 A ",isplay"" "Field_C" FROM * ')'&( &OA-(* "+," 4 A "&ou%t"" "Field_C" FROM "(able" @1'R' "+," +* ')'&( "(able"."+," FROM "Filter"" "(able" @1'R' "(able"."Field_D" E +F-A))* "Filter"."Filter_D"" "(able"."Field_D" 4 4 8ROA. !/ "Field_C" 4
OR,'R !/ "Field_C"

This *ery comple6 @uery can be bro,en down. ?n practice it is common to use a VIE! or the subG @uery. The listbo6 recei*es its content rom a @uery relating to this VIE!H The @uery in detail' The @uery presents two columns. The irst column contains the *iew seen by a person who has the orm open. This *iew shows the content o the ield and) separated by a hyphen) the hits or this ield content. The second column trans ers its content to the underlying table o the orm. /ere we ha*e only the content o the ield. The listbo6es thus draw their content
3hapter , ;acros 8((

rom the @uery) which is presented as the ilter result in the orm. :nly these ields are a*ailable or urther iltering. The table rom which this in ormation is drawn is actually a @uery. ?n this @uery the primary ,ey ields are counted & ELECT COUNT( "ID" ) A "C-=(t"(. This is then grouped by the search term in the ield &+ROUP BY ""%e&'_E"(. This @uery presents the term in the ield itsel as the second column. This @uery in turn is based on a urther subG@uery' ')'&( "(able"."+," FROM "Filter"" "(able" @1'R' "(able"."Field_D" E +F-A))* "Filter"."Filter_D"" "(able"."Field_D" 4 This subG@uery deals with the other ield to be iltered. ?n principle) this other ield must also match the primary ,ey. ? there are urther ilters) this @uery can be e6tended' ')'&( "(able"."+," FROM "Filter"" "(able" @1'R' "(able"."Field_D" E +F-A))* "Filter"."Filter_D"" "(able"."Field_D" 4 A-, "(able"."Field_R" E +F-A))* "Filter"."Filter_R"" "(able"."Field_R" 4 This allows any urther ields that are to be iltered to control what inally appears in the listbo6 o the irst ield) W5ieldL1W. 5inally the whole @uery is sorted by the underlying ield. 7hat the inal @uery underlying the displayed orm) actually loo,s li,e) can be seen rom Chapter <) 2atabase Tas,s. The ollowing macro can control through a listbo6 which listbo6es must be sa*ed and which must be read in again. The ollowing subroutine assumes that the I+dditional in ormationJ property or each listbo6 contains a commaGseparated list o all listbo6 names with no spaces. The irst name in the list must be the name o that listbo6.
A! Filter_more_i%<o*o've%t A O!L'&(4 ,+M o,oc A O!L'&( ,+M o,rawpa$e A O!L'&( ,+M oFormC A O!L'&( ,+M oFormD A O!L'&( ,+M oField)istC A O!L'&( ,+M oField)istD A O!L'&( ,+M s(a$ A tri%$ s(a$ E o've%t. ource.Model.(a$

+n array &a collection o data accessible *ia an inde6 number( is established and illed with the ield names o the listbo6es. The irst name in the list is the name o the listbo6 lin,ed to the e*ent.
a)ist*4 E plit*s(a$" """4 o,oc E this&ompo%e%t o,rawpa$e E o,oc.drawpa$e oFormC E o,rawpa$e.<orms.$et!y-ame*"Filter"4 oFormD E o,rawpa$e.<orms.$et!y-ame*",isplay"4

The array is run through rom its lower bound &AL0-=('()A( to its upper bound &AU0-=('()A( in a single loop. +ll *alues which were separated by commas in the additional in ormation) are now trans erred successi*ely.
FOR i E )!ou%d*a)ist*44 (O A!ou%d*a)ist*44 +F i E 3 (1'-

The listbo6 that triggered the macro must be sa*ed. ?t is ound in the *ariable )L%st(0). 5irst the in ormation or the listbo6 is carried across to the underlying table) and then the record is sa*ed.
oFormC.$et!y-ame*a)ist*i44.commit*4 oFormC.updateRow*4 ') '

8(8

Base Handbook

The other listbo6es must be re reshed) as they now contain di erent *alues depending on the irst listbo6.
oFormC.$et!y-ame*a)ist*i44.re<resh*4 '-, +F -':( oFormD.reload*4 '-, A!

The @ueries or this more usable macro are naturally the same as those already presented in the pre*ious section.

?earching data records


You can search database records without using a macro. /owe*er) the corresponding @uery that must be set up can be *ery complicated. + macro can sol*e this problem with a loop. The ollowing subroutine reads the ields in a table) creates a @uery internally) and inally writes a list o primary ,ey numbers o records in the table that are retrie*ed by this search term. ?n the ollowing description) there is a table called .earchtmp) which consists o an autoGincrementing primary ,ey ield &?2( and a ield called "r. that contains all the primary ,eys retrie*ed rom the table being searched. The table name is supplied initially to the subroutine as a *ariable. To get a correct result) the table must contain the content you are searching or as te6t and not as oreign ,eys. ? necessary) you can create a V?F7 or the macro to use.
A! earch*st(able A (R+-84 ,+M o,ata ource A O!L'&( ,+M o&o%%ectio% A O!L'&( ,+M o B)_ tateme%t A O!L'&( ,+M st Tl A (R+-8 ,+M oBuery_Result A O!L'&( ,+M o,oc A O!L'&( ,+M o,rawpa$e A O!L'&( ,+M oForm A O!L'&( ,+M oFormD A O!L'&( ,+M oField A O!L'&( ,+M st&o%te%t A (R+-8 ,+M ar&o%te%t*4 A (R+-8 ,+M i%+ A +-('8'R ,+M i%# A +-('8'R o,oc E this&ompo%e%t o,rawpa$e E o,oc.drawpa$e oForm E o,rawpa$e.<orms.$et!y-ame*" earch<orm"4 oField E oForm.$et!y-ame*" earchtext"4 st&o%te%t E oField.$et&urre%t0alue*4 st&o%te%t E )&ase*st&o%te%t4

The content o the search te6t ield is initially con*erted into lower case so that the subse@uent search unction need only compare lower case spellings.
o,ata ource E (his&ompo%e%t..are%t.,ata ource o&o%%ectio% E o,ata ource.8et&o%%ectio%*"""""4 o B)_ tateme%t E o&o%%ectio%.create tateme%t*4

5irst it must be determined i a search term has actually been entered. ? the ield is empty) it will be assumed that no search is re@uired. +ll records will be displayed without urther searching. ? a search term has been entered) the column names are read rom the table being searched) so that the @uery can access the ields.
+F st&o%te%t ;= "" (1'-

3hapter , ;acros

8(

st Tl E " ')'&( ""&O)AM-_-AM'"" FROM ""+-FORMA(+O-_ &1'MA""."" / ('M_&O)AM- "" @1'R' ""(A!)'_-AM'"" E G" H st(able H "G OR,'R !/ ""OR,+-A)_.O +(+O-""" oBuery_Result E o B)_ tateme%t.executeBuery*st Tl4

9ote

.D% ormulas in macros must irst be placed in double @uotes li,e normal character strings. 5ield names and table names are already in double @uotes inside the .D% ormula. To create inal code that transmits the double @uotes properly) ield names and table names must be gi*en two sets o these @uotes. st Tl E " ')'&( ""-ame"" FROM ""(able""5" becomes) when displayed with the command ms$box st Tl) ELECT "N)*e" "ROM "T)0&e"

The inde6 o the array) in which the ield names are written is initially set to 0. Then the @uery begins to be read out. +s the si0e o the array is un,nown) it must be adRusted continuously. That is why the loop begins with AReD%* P/ese/:e )/C-(te(t(%(I)A to set the si0e o the array and at the same time to preser*e its e6isting contents. "e6t the ields are read and the array inde6 incremented by 1. Then the array is dimensioned again and a urther *alue can be stored.
+%+ E 3 +F -O( + -A))*oBuery_Result4 (1'@1+)' oBuery_result.%ext Re,im .reserve ar&o%te%t*i%+4 ar&o%te%t*i%+4 E oBuery_Result.$et tri%$*C4 i%+ E i%+ H C @'-, '-, +F st Tl E ",RO. (A!)' "" earchtmp"" +F ':+ ( " o B)_ tateme%t.executeApdate *st Tl4

"ow the @uery is put together within a loop and subse@uently applied to the table de ined at the beginning. +ll case combinations are allowed or) since the content o the ield in the @uery is con*erted to lower case. The @uery is constructed such that the results end up in the .earchtmp table. ?t is assumed that the primary ,ey is the irst ield in the table &)/C-(te(t(0)(.
st Tl E " ')'&( """Har&o%te%t*34H""" +-(O "" earchtmp"" FROM """ H st(able H """ @1'R' " FOR i%# E 3 (O *i%+ F C4 st Tl E st TlH")&ase*"""Har&o%te%t*i%#4H"""4 )+#' GQ"Hst&o%te%tH"QG" +F i%# ; *i%+ F C4 (1'st Tl E st TlH" OR " '-, +F -':( o B)_ tateme%t.executeBuery*st Tl4 ') ' st Tl E ",')'(' FROM "" earchtmp""" o B)_ tateme%t.executeApdate *st Tl4 '-, +F

The display orm must be reloaded. ?ts data source is a @uery) in this e6ample .earch@uery.
oFormD E o,rawpa$e.<orms.$et!y-ame*",isplay"4 oFormD.reload*4 '%d ub

This creates a table that is to be e*aluated by the @uery. +s ar as possible) the @uery should be constructed so that it can subse@uently be edited. + sample @uery is shown'

8(!

Base Handbook

')'&( I FROM " earchtable" @1'R' "-r." +- * ')'&( "-r." FROM " earchtmp" 4 OR "-r." E &A ' @1'- * ')'&( &OA-(* "-r." 4 FROM " earchtmp" 4 = 3 (1'- G3G ') ' "-r." '-, +ll elements o the e)/7.t)0&e are included) including the primary ,ey. "o other table appears in the direct @ueryP there ore no primary ,ey rom another table is needed and the @uery result remains editable. The primary ,ey is sa*ed in this e6ample under the name N/H The macro reads precisely this ield. There is an initial chec, to see i the content o the N/H ield appears in the e)/7.t*< table. The IN operator is compatible with multiple *alues. The subG@uery can also yield se*eral records. 5or larger amounts o data) *alue matching by using the IN operator @uic,ly slows down. There ore it is not a good idea to use an empty search ield simply to trans er all primary ,ey ields rom e)/7.t)0&e into the e)/7.t*< table and then *iew the data in the same way. ?nstead an empty search ield creates an empty e)/7.t*< table) so that no records are a*ailable. This is the purpose o the second hal o the condition' OR "-r." E &A ' @1'- * ')'&( &OA-(* "-r." 4 FROM " earchtmp" 4 = 3 (1'- GFCG ') ' "-r." '-, ? a record is ound in the .earchtmp table) it means that the result o the irst @uery is greater than 0. ?n this case' "N/H" N A>EA &here we need a number which cannot occur as a primary ,ey) so A>EAis a $ood value(. ? the @uery yields precisely 0 &which will be the case i no records are present() then "N/H" N "N/H". This will list e*ery record which has a N/H +s N/H is the primary ,ey) this means all records.

Combobo/es as listbo/es with an entry option


+ table with a single record can be directly created by using combobo6es and in*isible numeric ields and the corresponding primary ,ey entered into another table. ?n pre*ious *ersions o %ibre: ice or :pen: ice.org) it was necessary to ma,e the numeric ields in*isible by using a macro. This is no longer necessary in %ibre: ice as the =*isible= property is now contained in the !#?. The Combobo6 control treats orm ields or combined entry and choice o *alues &combobo6es( as listbo6es with an entry option. 5or this purpose) in addition to the combobo6es in the orm) the ,ey ield *alues which are to be trans erred to the underlying table are stored in separate numeric ields. These ields) prior to :pen: ice.org 3.3) had to ha*e the cin*isibleK switch set) as the unction was not accessible rom orm design. This is no longer necessary in %ibre: ice and :pen: ice.org 3.3. 5ields can now be declared as in*isible. The ,eys rom these ields are read in when the orm is loaded and the combobo6 is set to show the corresponding content. ? the content o the combobo6 is changed) it is sa*ed and the new primary ,ey is trans erred into the corresponding numeric ield to be stored in the main table. The original o this module is in the e6ample database) as e6panded with macros.

$ext dis lay in comboboxes


This subroutine is to show te6t in the combobo6 according to the *alue o the in*isible oreign ,ey ields rom the main orm. ?t can also be used or listbo6es which re er to two di erent tables. This might happen i ) or e6ample) the postcode in a postal address is stored separately rom the town. ?n that case the postcode might be read rom a table that contains only a oreign ,ey or the town. The listbo6 should show postcode and town together.
A! (ext,isplay*-ameForm A (R+-8" -ame ub<orm A (R+-8" -ame ub ub<orm A (R+-8" -ameField A (R+-8" -ame+,Field A (R+-8" -ame(ableFieldC A (R+-8" -ame(ableFieldD A (R+-8" Fieldseparator A (R+-8" -ame(ableC A

3hapter , ;acros

8("

(R+-8" O.(+O-A) -ame(ableD A O.(+O-A) .ositio% A +-('8'R 4

(R+-8" O.(+O-A) -ame(abCD+, A

(R+-8"

This macro should be bound to the ollowing orm e*ents' =7hen loading= and =+ ter record change=. The ollowing parameters are optional and need not be gi*en when the subroutine is called. To pre*ent a runtime error) de ault *alues must be prede ined.
+F isMissi%$*-ame(ableD4 (1'- -ame(ableD E "" +F isMissi%$*-ame(abCD+,4 (1'- -ame(abCD+, E "" +F isMissi%$*.ositio%4 (1'- .ositio% E D

The I" condition here is only one line) so it does not re@uire an END I". + ter this) the *ariables are declared. .ome *ariables ha*e already been declared globally in a separate module and are not declared here again.
,+M oForm A O!L'&( ,+M o ubForm A O!L'&( ,+M o ub ubForm A O!L'&( ,+M oField A O!L'&( ,+M oField)ist A O!L'&( ,+M stField0alue A (R+-8 ,+M i%+, A +-('8'R ,+M o&tl0iew A O!L'&( o,oc E this&ompo%e%t o,rawpa$e E o,oc.,rawpa$e oForm E o,rawpa$e.<orms.$et!y-ame*-ameForm4

The position o the ield in the corresponding orm is determined. +ll orms are held on the D/)S<)Be o the current document t.%sC-*<-(e(t. This subroutine uses arguments to co*er the possibility that the ield is contained in a sub orm o a sub orm) that is two le*els down rom the actual orm. The ield that contains the oreign ,ey is named -"%e&'. The combobo6) which now e6ists instead o a listbo6 is named -"%e&'L%st.
+F -ame ub<orm ;= "" (1'o ubForm E oForm.$et!y-ame*-ame ub<orm4 +F -ame ub ub<orm ;= "" (1'o ub ubForm E o ubForm.$et!y-ame*-ame ub ub<orm4 oField E o ub ubForm.$et!y-ame*-ame+,Field4 oField)ist E o ub ubForm.$et!y-ame*-ameField4 ') ' oField E o ubForm.$et!y-ame*-ame+,Field4 oField)ist E o ubForm.$et!y-ame*-ameField4 '-, +F ') ' oField E oForm.$et!y-ame*-ame+,Field4 oField)ist E oForm.$et!y-ame*-ameField4 '-, +F oField)ist.Re<resh*4

The combobo6 is read in again using ReC/es.(). ?t might be that the content o the ield has been changed by the entry o new data. This must be made possible. + ter this) the *alue o the oreign ,ey is read. :nly i a *alue is entered here will a connection be made to the data source.
+F -O( +s'mpty*oField.$et&urre%t0alue*44 (1'i%+, E oField.$et&urre%t0alue*4 o,ata ource E (his&ompo%e%t..are%t.&urre%t&o%troller +F -O( *o,ata ource.is&o%%ected*44 (he% o,ata ource.co%%ect*4 '%d +F o&o%%ectio% E o,ata ource.Active&o%%ectio%*4

8(#

Base Handbook

o B)_ tateme%t E o&o%%ectio%.create tateme%t*4

The .D% statement is ormulated according to the ields used in the combobo6. This re@uires the testing o *arious combinations. The most general is that the combobo6 must be pro*ided with a @uery that re ers to two table ields rom di erent tables. This subroutine is not designed or urther possibilities. The test begins with this most important possibility.
+F -ame(ableFieldD ;= "" (1'-

? a second table ield e6ists)


+F -ame(ableD ;= "" (1'-

... and i a second table e6ists) the ollowing .D% code will be produced'
+F .ositio% E D (1'st Tl E " ')'&( """ H -ame(ableC H """.""" H -ame(ableFieldC H """77G" H Fieldseparator H "G77""" H -ame(ableD H """.""" H -ame(able%FieldD H """ FROM """ H -ame(ableC H """"""" H -ame(ableD H """ @1'R' ""+,""EG" Hi%+,H "G A-, """ H -ame(ableC H """.""" H -ame(abCD+, H """E""" H -ame(ableD H """.""+,""" ') ' st Tl E " ')'&( """ H -ame(ableD H """.""" H -ame(ableFieldD H """77G" H Fieldseparator H "G77""" H -ame(ableC H """.""" H -ame(ableFieldC H """ FROM """ H -ame(ableC H """"""" H -ame(ableD H """ @1'R' ""+,""EG" H i%+, H "G A-, """ H -ame(ableC H """.""" H -ame(abCD+, H """E""" H -ame(ableD H """.""+,""" '-, +F

7hen written out in the orm re@uired by 9asic) this .D% command is pretty incomprehensible. Fach ield and each table name must be written into the .D% input with two sets o double @uotes as shown abo*e. +s double @uotes are normally interpreted by 9asic as indicating te6t) they disappear when the code is trans erred. :nly when a second set o double @uotes is used are terms passed on in simple @uotes. ""ID"" there ore means that the "ID" ield &with a single set o @uotation mar,s or the .D% relationship( is accessed in the @uery. + partial simpli ication or this subroutine is that all primary ,eys in this database carry the name ?2. The code is urther complicated by the act that) as well as re@uiring duplicate @uotation mar,s) some o the included table ields are entered as *ariables. These are not te6tP they are simply concatenated with the preceding te6t by using N . 9ut these *ariables must also be mas,ed. That is why these *ariables are shown abo*e with three sets o @uotation mar,s' """UN)*eT)0&eEU"""H"""UN)*eT)0&e"%e&'EU""" inallly translates into the amiliar @uery language "T)0&eE"H""%e&'E". 5ortunately when we create the macro) the coloring o the code shows i any double @uotes ha*e been omitted. The @uotation mar,s change their color immediately i they are not recognised by the macro as string delimiters.
') '

... and i the second table does not e6ist) the ollowing .D% code is created'
+F .ositio% E D (1'st Tl E " ')'&( """ "G77""" H -ame(ableFieldD i%+, H "G" ') ' st Tl E " ')'&( """ "G77""" H -ame(ableFieldC i%+, H "G" '-, +F '-, +F ') ' H -ame(ableFieldC H """77G" H Fieldseparator H H """ FROM """ H -ame(ableC H """ @1'R' ""+,""EG" H H -ame(ableFieldD H """77G" H Fieldseparator H H """ FROM """ H -ame(ableC H """ @1'R' ""+,""EG" H

? a second table ield does not e6ist there can be only one table. This yields the ollowing @uery'
st Tl E " ')'&( """ H -ame(ableFieldC H """ FROM """ H -ame(ableC H """ @1'R' ""+,""EG" H i%+, H "G" '-, +F

3hapter , ;acros

8(9

The @uery stored in the *ariable st O& is now run and the result o the @uery is stored in the *ariable -$=e/J_/es=&t.
oBuery_result E o B)_ tateme%t.executeBuery*st Tl4

The @uery result is read in a loop. /ere) as in !#? @ueries) se*eral ields and records can be created. 9ut the construction o this @uery will produce only one result. This result will be ound in the irst column (E) o the @uery. ?t is the record which pro*ides the content which the combobo6 is to display. The content is a te6t string &ABet t/%(B()A() so here we see A-$=e/J_/es=&tHBet t/%(B(E)A.
+F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext stField0alue E oBuery_result.$et tri%$*C4 @'-,

The combobo6 must now be set to the te6t *alues resulting rom the @uery. This re@uires access to the Controller.
o,oc&rl E (his&ompo%e%t.$et&urre%t&o%troller*4 o&tl0iew E o,oc&rl.8et&o%trol*oField)ist4 o&tl0iew.set(ext*stField0alue4 '-, +F '-, +F

? there is no *alue in the ield or the oreign ,ey =o5ield=) it means that the @uery has ailed. The combobo6 is then set to an empty display.
+F +s'mpty*oField.$et&urre%t0alue*44 (1'o,oc&rl E (his&ompo%e%t.$et&urre%t&o%troller*4 o&tl0iew E o,oc&rl.8et&o%trol*oField)ist4 o&tl0iew.set(ext*""4 '-, +F '-, A!

This subroutine handles the contact between the oreign ,eys in a hidden ield and the combobo6. This is su icient or the display o the correct *alues in the combobo6. To store a new *alue re@uires a urther subroutine.

$ransferin# a forei#n key value from a combobox to a numeric field


? a new *alue is entered into the combobo6 &and this a ter all is the purpose or which this macro was constructed() the corresponding primary ,ey must be entered into the orm=s underlying table as a 5oreign ,ey.
A! (ext&hoice0alue ave*-ameForm A (R+-8" -ame ub<orm A (R+-8" -ame ub ub<orm A (R+-8" -ameField A (R+-8" -ame+,Field A (R+-8" -ame(ableFieldC A (R+-8" -ame(ableFieldD A (R+-8" Field eparator A (R+-8" -ame(ableC A (R+-8" O.(+O-A) -ame(ableD A (R+-8" O.(+O-A) -ame(abCD+, A (R+-8" O.(+O-A) .ositio% A +-('8'R 4

This macro should be bound to the ollowing orm e*ent' =9e ore record action=. The start o this unction corresponds in principle with the pre*iously described subroutine. /ere too there are optional *ariables.
+F isMissi%$*-ame(ableD4 (1'- -ame(ableD E "" +F isMissi%$*-ame(abCD+,4 (1'- -ame(abCD+, E "" +F isMissi%$*.ositio%4 (1'- .ositio% E D

+ ter this the other *ariables are declared) those that ha*e not yet been declared outside the subroutine or unction. Then the orm is loaded and the rele*ant ields are allocated to *ariables. The ield -"%e&' contains the oreign ,ey and -"%e&'L%st shows the corresponding te6t.
,+M oForm A O!L'&( ,+M o ubForm A O!L'&(

8()

Base Handbook

,+M ,+M ,+M ,+M ,+M ,+M ,+M ,+M ,+M ,+M ,+M ,+M

o ub ubForm A O!L'&( oField A O!L'&( oField)ist A O!L'&( st&o%te%t A (R+-8 st&o%te%tFieldD A (R+-8 a_st.art*4 A (R+-8 stms$boxC A (R+-8 stms$boxD A (R+-8 i%+,C A +-('8'R i%+,D A +-('8'R FieldC)e%$th A +-('8'R FieldD)e%$th A +-('8'R

The ma6imum length allowed or an entry is determined using the unction Columnsi0e) described below. -ust setting a limit on the si0e o the combobo6 is not sa e here) as we need to include the possibility o entering two ields together.
FieldC)e%$th E &olum%siUe*-ame(ableC"-ame(ableFieldC4 +F -ame(ableFieldD ;= "" (1'+F -ame(ableD ;= "" (1'FeldD)e%$th E &olum%siUe*-ame(ableD"-ame(ableFieldD4 ') ' FeldD)e%$th E &olum%siUe*-ame(ableC"-ame(ableFieldD4 '-, +F ') ' FeldD)e%$th E 3 '-, +F

The orm is loaded) and the comobo6 is read.


o,oc E this&ompo%e%t o,rawpa$e E o,oc.,rawpa$e oForm E o,rawpa$e.Forms.$et!y-ame*-ameForm4 +F -ame ub<orm ;= "" (1'o ubForm E oForm.$et!y-ame*-ame ub<orm4 +F -ame ub ub<orm ;= "" (1'o ub ubForm E o ubForm.$et!y-ame*-ame ub ub<orm4 oField E o ub ubForm.$et!y-ame*-ame+,Field4 oField)ist E o ub ubForm.$et!y-ame*-ameField4 ') ' oField E o ubForm.$et!y-ame*-ame+,Field4 oField)ist E o ubForm.$et!y-ame*-ameField4 '-, +F ') ' oField E oForm.$et!y-ame*-ame+,Field4 oField)ist E oForm.$et!y-ame*-ameField4 '-, +F st&o%te%t E oField)ist.$et&urre%t0alue*4

The displayed content o the combobo6 is read. %eading and trailing spaces and nonGprinting characters are remo*ed i necessary.
t&o%te%t E (rim*st&o%te%t4 +F st&o%te%t ;= "" (1'+F -ame(ableFieldD ;= "" (1'-

? a second table ield e6ists) the content o the combobo6 must be split. To determine where the split is to occur) we use the ield separator pro*ided to the unction as an argument.
a_st.art E plit*st&o%te%t" Field eparator" D4

The last parameter signi ies that the ma6imum number o parts is 2. 2epending on which entry corresponds to ield 1 and which to ield 2) the content o the combobo6 is now allocated to the indi*idual *ariables. W$osition Y 2W ser*es here as a sign that the second part o the content stands or 5ield 2.
3hapter , ;acros 8(,

+F .ositio% E D (1'st&o%te%t E (rim*a_st.art*344 +F A!ou%d*a_st.art*44 = 3 (1'st&o%te%tFieldD E (rim*a_st.art*C44 ') ' st&o%te%tFieldD E "" '-, +F st&o%te%tFieldD E (rim*a_st.art*C44 ') ' st&o%te%tFieldD E (rim*a_st.art*344 +F A!ou%d*a_st.art*44 = 3 (1'st&o%te%t E (rim*a_st.art*C44 ') ' st&o%te%t E "" '-, +F st&o%te%t E (rim*a_st.art*C44 '-, +F '-, +F

?t can happen that with two separable contents) the installed si0e o the combobo6 &te6t length( does not it the table ields to be sa*ed. 5or combobo6es that represent a single ield) this is normally handled by suitably con iguring the orm control. /ere by contrast) we need some way o catching such errors. The ma6imum permissible length o the rele*ant ield is chec,ed.
+F *FieldC)e%$th = 3 A-, )e%*st&o%te%t4 = FieldC)e%$th4 OR *FieldD)e%$th = 3 A-, )e%*st&o%te%tFieldD4 = FieldD)e%$th4 (1'-

? the ield length o the irst or second part is too big) a de ault string is stored in one o the *ariables. The character CHR(EG) is used to put in a line brea, .
stms$boxC E "(he <ield " H -ame(ableFieldC H " must %ot exceed " H FieldC)e%$th H "characters i% le%$th." H &1R*CR4 stms$boxD E "(he <ield " H -ame(ableFieldD H " must %ot exceed " H FieldD)e%$th H "characters i% le%$th." H &1R*CR4

? both ield contents are too long) both te6ts are displayed.
+F *FieldC)e%$th = 3 A-, )e%*st&o%te%t4 = FieldC)e%$th4 A-, *FieldD)e%$th = 3 A-, )e%*st&o%te%tFieldD4 = FieldD)e%$th4 (1'ms$box *"(he e%tered text is too lo%$." H &1R*CR4 H stms$boxC H stms$boxD H ".lease shorte% it.""VN""+%valid e%try"4

The display uses the *sB0-x() unction. This e6pects as its irst argument a te6t string) then optionally a number &which determines the type o message bo6 displayed() and inally an optional te6t string as a title or the window. The window will there ore ha*e the title W?n*alid entryW and the number =C4= pro*ides a bo6 containing the ?n ormation symbol. The ollowing code co*ers any urther cases o e6cessi*ely long te6t that might arise.
') '+F *FieldC)e%$th = 3 A-, )e%*st&o%te%t4 = FieldC)e%$th4 (1'ms$box *"(he e%tered text is too lo%$." H &1R*CR4 H stms$boxC H ".lease shorte% it.""VN""+%valid e%try"4 ') ' ms$box *"(he e%tered text is too lo%$." H &1R*CR4 H stms$boxD H ".lease shorte% it.""VN""+%valid e%try"4 '-, +F ') '

? there is no e6cessi*ely long te6t) the unction can proceed. :therwise it e6its here. 5irst *ariables are preallocated which can subse@uently be altered by the @uery. The *ariables in?21 and in?22 store the content o the primary ,ey ields o the two tables. ? a @uery yields no results) 9asic assigns these integer *ariable a *alue o 0. /owe*er this *alue could also indicate a success ul @uery returning a primary ,ey *alue o 0P there ore the *ariable is preset to G1. /.D%29 cannot set this *alue or an auto*alue ield.

887

Base Handbook

"e6t the database connection is set up) i it does not already e6ist.
i%+,C E FC i%+,D E FC o,ata ource E (his&ompo%e%t..are%t.&urre%t&o%troller +< -O( *o,ata ource.is&o%%ected*44 (he% o,ata ource.co%%ect*4 '%d +< o&o%%ectio% E o,ata ource.Active&o%%ectio%*4 o B)_ tateme%t E o&o%%ectio%.create tateme%t*4 +F -ame(ableFieldD ;= "" A-, -O( +s'mpty*st&o%te%tFieldD4 A-, -ame(ableD ;= "" (1'-

? a second table ield e6ists) a second dependency must irst be declared.


st Tl E " ')'&( ""+,"" FROM """ H -ame(ableD H """ @1'R' """ H -ame(ableFieldD H """EG" H st&o%te%tFieldD H "G" oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext i%+,D E oBuery_result.$et+%t*C4 @'-, '-, +F +F i%+,D E FC (1'st Tl E "+- 'R( +-(O """ H -ame(ableD H """ *""" H -ame(ableFieldD H """4 0A)A' *G" H st&o%te%tFieldD H "G4 " o B)_ tateme%t.executeApdate*st Tl4 st Tl E "&A)) +,'-(+(/*4"

? the content within the combobo6 is not present in the corresponding table) it is inserted there. The primary ,ey *alue which results is then read. ? it is present) the e6isting primary ,ey is read in the same way. The unction uses the automatically generated primary ,ey ields &IDENTITY(.
oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext i%+,D E oBuery_result.$et+%t*C4 @'-, '-, +F '-, +F

The primary ,ey or the second *alue is temporarily stored in the *ariable %(ID8 and then written as a oreign ,ey into the table corresponding to the irst *alue. +ccording to whether the record rom the irst table was already a*ailable) the content is reshly sa*ed &IN ERT( or altered &UPDATE('
+F i%+,C st Tl -ame(ableFieldC H H i%+,D H "G4 " o B)_ E FC (1'E "+- 'R( +-(O """ H -ame(ableC H """ *""" H """"""" H -ame(abCD+, H """4 0A)A' *G" H st&o%te%t H "G"G" tateme%t.executeApdate*st Tl4

+nd the corresponding ?2 directly read out'


st Tl E "&A)) +,'-(+(/*4" oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext i%+,C E oBuery_result.$et+%t*C4 @'-, '-, +F

The primary ,ey or the irst table must inally be read again so that it can be trans erred to the orm=s underlying table.
') '

3hapter , ;acros

88(

st Tl E "A.,A(' """ H -ame(ableC H """ '( """ H -ame(abCD+, H """EG" H i%+,D H "G @1'R' """ H -ame(ableFieldC H """ E G" H st&o%te%t H "G" o B)_ tateme%t.executeApdate*st Tl4 '-, +F '-, +F

?n the case where both the ields underlying the combobo6 are in the same table & or e6ample .urname and 5irstname in the "ame table() a di erent @uery is needed'
+F -ame(ableFieldD ;= "" A-, -ame(ableD E "" (1'st Tl E " ')'&( ""+,"" FROM """ H -ame(ableC H """ @1'R' """ H -ame(ableFieldC H """EG" H st&o%te%t H "G A-, """ H -ame(ableFieldD H """EG" H st&o%te%tFieldD H "G" oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oAb<ra$eer$eb%is4 (1'@1+)' oBuery_result.%ext i%+,C E oBuery_result.$et+%t*C4 @'-, '-, +F +F i%+,C E FC (1'-

... and a second table does not e6ist'


st Tl E "+- 'R( +-(O """ H -ame(ableC H """ *""" H -ame(ableFieldC H """"""" H -ame(ableFieldD H """4 0A)A' *G" H st&o%te%t H "G"G" H st&o%te%tFieldD H "G4 " o B)_ tateme%t.executeApdate*st Tl4

Then the primary ,ey is read again.


st Tl E "&A)) +,'-(+(/*4" oTuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext i%+,C E oBuery_result.$et+%t*C4 @'-, '-, +F '-, +F '-, +F +F -ame(ableFieldD E "" (1'-

"ow we consider the simplest case' The second table ield does not e6ist and the entry is not yet present in the table. ?n other words) a single new *alue has been entered into the combobo6.
st Tl E " ')'&( ""+,"" FROM """ H -ame(ableC H """ @1'R' """ H -ame(ableFieldC H """EG" H st&o%te%t H "G" oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext i%+,C E oBuery_result.$et+%t*C4 @'-, '-, +F +F i%+,C E FC (1'-

? there is no second ield) the content o the bo6 is inserted as a new record.
st Tl E "+- 'R( +-(O """ H -ame(ableC H """ *""" H -ame(ableFieldC H """4 0A)A' *G" H st&o%te%t H "G4 " o B)_ tateme%t.executeApdate*st Tl4

] and the resulting ?2 directly read out.


st Tl E "&A)) +,'-(+(/*4" oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( + -A))*oBuery_result4 (1'@1+)' oBuery_result.%ext i%+,C E oBuery_result.$et+%t*C4

888

Base Handbook

@'-, '-, +F '-, +F '-, +F

The *alue o the primary ,ey ield must be determined) so that it can be trans erred to the main part o the orm. "e6t the primary ,ey *alue that has resulted rom all these loops is trans erred to the in*isible ield in the main table and the underlying database. The table ield lin,ed to the orm ield is reached by using AB-=('"%e&'A. A=<')teI(tA places an integer &see under numerical type de initions( in this ield.
oField.!ou%dField.update+%t*i%+,4 '-, +F ') '

? no primary ,ey is to be entered) because there was no entry in the combobo6 or that entry was deleted) the content o the in*isible ield must also be deleted. =<')teN=&&() is used to ill the ield with the databaseGspeci ic e6pression or an empty ield) NULL.
oField.!ou%dField.update-ull*4 '-, +F '-, A!

'unction to measure the len#th of the combobox entry


The ollowing unction gi*es the number o characters in the respecti*e table column) so that entries that are too long do not Rust get truncated. + "UNCTION is chosen here to pro*ide return *alues. + UB has no return *alue that can be passed on and processed elsewhere.
FA-&(+O- &olum% iUe*(able%ame A (R+-8" Field%ame A (R+-84 A +-('8'R o,ata ource E (his&ompo%e%t..are%t.&urre%t&o%troller +< -O( *o,ata ource.is&o%%ected*44 (he% o,ata ource.co%%ect*4 '%d +< o&o%%ectio% E o,ata ource.Active&o%%ectio%*4 o B)_ tateme%t E o&o%%ectio%.create tateme%t*4 st Tl E " ')'&( ""&O)AM-_ +W'"" FROM ""+-FORMA(+O-_ &1'MA""."" / ('M_&O)AM- "" @1'R' ""(A!)'_-AM'"" E G" H (able%ame H "G A-, ""&O)AM-_-AM'"" E G" H Field%ame H "G" oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( +s-ull*oBuery_result4 (1'@1+)' oBuery_result.%ext i E oBuery_result.$et+%t*C4 @'-, '-, +F &olum%siUe E i '-, FA-&(+O-

"allin# the subroutine for dis layin# texts


The subroutine or creating the combobo6 is called each time a record is changed. The ollowing e6ample shows this or the sample database.
A! Form_Reader_+%put_)oad R'M (ext,isplay*-ameForm A (R+-8" -ame ubForm A (R+-8" -ame ub ubForm A (R+-8" -ameField A (R+-8" -ame+,Field A (R+-8" -ame(ableFieldC*<rom (able C4 A (R+-8" -ame(ableFieldD*<rom (able C or <rom (able D4 A (R+-8" Field eparator A (R+-8" -ame(ableC A (R+-8" O.(+O-A) -ame(ableD A (R+-8" O.(+O-A) -ame+,From(ableD+%(ableC A (R+-8" O.(+O-A) Field .ositio% <rom the tableD i% the &ombobox A +-('8'R 6C or D9 4 (ext,isplay *"Filter"" "Form"" "Address"" "com tr"" "%um tr+,"" " treet"" """ """ " treet"4 3hapter , ;acros 88

(ext,isplay *"Filter"" "Form"" "Address"" "com.lc(ow%"" "%um.lc(ow%+,"" ".ostcode"" "(ow%"" " "" ".ostcode"" "(ow%"" "(ow%_+,"" D4 '-, A!

The comment lines show the list o parameters that need to be pro*ided or the subroutine. +n empty parameter is represented by a pair o double @uotes. The last three parameters are optional as they are co*ered where necessary by de ault *alues in the subroutine. The TextD%s<&)J subroutine is called. The orm that contains the ields is "%&te/ 1 "-/* 1 A''/ess. 7e are there ore dealing with the sub orm o a sub orm. The irst combobo6) in which the street is entered) is called 7-* t/) the hidden oreign ,ey ield in the table underlying the orm is called (=* t/ID. ?n this irst combobo6 the ield t/eet is displayed. The table) which will contain the entries rom the combobo6) is also called t/eet. The town and postcode are entered into the second combobo6. This is called 7-*P&7T-S(. The hidden oreign ,ey ield is called (=*P&7T-S(ID. This second combobo6 contains the P-st7-'e and T-S() separated by a space &" "(. The irst table has the name P-st7-'e) the second table the name T-S(. ?n the irst table the oreign ,ey or the second table is called T-S(_ID. The ield or the second table is the second element in the combobo6) that is position 8.

"allin# the subroutine for text stora#e


To store the entry) we use the subroutine Te6tChoiceValue.a*e.
A! Form_Reader_Output_ ave R'M (ext&hoice0alue ave*-ameForm A (R+-8" -ame ubForm A (R+-8" -ame ub ubForm A (R+-8" -ameField A (R+-8" -ame+,Field A (R+-8" -ame(ableFieldC*<rom (able C4 A (R+-8" -ame(ableFieldD*<rom table C or table D4 A (R+-8" Field eparator A (R+-8"-ame(ableC A (R+-8" O.(+O-A) -ame(ableD A (R+-8" O.(+O-A) -ame+,From(ableD+%(ableC A (R+-8" O.(+O-A) .ositio% o< the <ield <rom (ableD i% the &ombobox A +-('8'R 6C or D9 4

The comment is similar to the one in the pre*ious subroutine. The *ariables being passed are also the same.
(ext&hoice0alue ave *"Filter"" "Form"" "Address"" "com tr"" "%um tr+,"" " treet"" """ """ " treet"" """ ""4 (ext&hoice0alue ave *"Filter"" "Form"" "Address"" "com.lc(ow%"" "%um.lc(ow%+,"" ".ostcode"" "(ow%"" " "" ".ostcode"" "(ow%"" "(ow%_+,"" D4 '-, A!

To sa ely store the *alue) the orm must be in ormed about changes. +s ar as the user is concerned) the change ta,es place only to the te6t inside the combobo6 to which the orm has no urther connection. 1ather it is the numeric ield containing the oreign ,ey that is the lin, to the database. .o the oreign ,ey is simply assigned the *alue G1) which an auto*alue ield cannot legally ha*e. This ensures a change in the ield content. This ield content is then copied o*er by the normal operation o the listbo6.
A! RecordActio%_produce*o've%t A O!L'&(4

This macro should be bound to the ollowing e*ent or the listbo6' =:n ocus=. ?t is necessary so that the sa*e operation ta,es place in all cases where the listbo6 content changes. 7ithout this macro there will be no change in the table) that 9ase can recognise) since the combobo6 is not lin,ed to the orm.
,+M oForm A O!L'&( ,+M o ubForm A O!L'&( ,+M o ub ubForm A O!L'&( ,+M oField A O!L'&( ,+M st(a$ A tri%$ st(a$ E o've%t. ource.Model.(a$ aForms*4 E plit*st(a$" """4

88!

Base Handbook

+n array is populatedP the ield name comes irst and then the orm names) with the main orm preceding the sub orm.
o,oc E this&ompo%e%t o,rawpa$e E o,oc.,rawpa$e oForm E o,rawpa$e.Forms.$et!y-ame*aForms*C44 +F A!ou%d*aForms*44 = C (1'oForm E oForm.$et!y-ame*aForms*D44 +F A!ou%d*aForms*44 = D (1'oForm E oForm.$et!y-ame*aForms*R44 '-, +F '-, +F oField E oForm.$et!y-ame*aForms*344 oField.!ou%dField.update+%t*FC4 '-, A!

9avigation from one form to another


+ orm is to be opened when a particular e*ent occurs. ?n the orm control properties) on the line W+dditional in ormationW &tag() enter the name o the orm. 5urther in ormation can also be entered here) and subse@uently separated out by using the <&%t() unction.
A! From_<orm_to_<orm*o've%t A O!L'&(4 ,+M st(a$ A tri%$ st(a$ E o've%t. ource.Model.(a$ aForm*4 E plit*st(a$" """4

The array is declared and illed with the orm names) irst the orm to be opened and secondly the current orm) which will be closed a ter the other has been opened.
(his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* (rim*aForm*344 4.ope% (his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* (rim*aForm*C44 4.close '-, A!

? instead) the other orm is only to be opened when the current one is closed) or e6ample where a main orm e6ists and all other orms are controlled rom it using buttons) the ollowing macro should be bound to the orm with $ools 5 CustomiPe 5 Bvents 5 #ocument closed'
A! Mai%<orm_ope% (his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* "Mai%<orm" 4.ope% '-, A!

? the orm documents are sorted within the :29 ile into directories) the macro or changing the orm needs to be more e6tensi*e'
A! From_<orm_to_<orm_with_<olders&o've%t A O!L'&(( R'M (he <orm to be ope%ed is $ive% <irst. R'M +< a <orm is i% a <older" use "/" to de<i%e the relatio%ship R'M so that the sub<older ca% be <ou%d. ,+M st(a$ A (R+-8 st(a$ E o've%t. ource.Model.(a$ G(a$ is e%tered i% the additio%al i%<ormatio% aForms*4 E plit*st(a$" """4 G1ere the <orm %ame <or the %ew <orm comes <irst" the% the o%e <or the old <orm aFormsC*4 E plit*aForms*34""/"4 aFormsD*4 E plit*aForms*C4""/"4 +F A!ou%d*aFormsC*44 E 3 (1'(his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* (rim*aFormsC*344 4.ope% ') ' (his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* (rim*aFormsC*344 4.$et!y-ame* (rim*aFormsC*C44 4.ope% '-, +F 3hapter , ;acros 88"

+F A!ou%d*aFormsD*44 E 3 (1'(his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* (rim*aFormsD*344 4.close ') ' (his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* (rim*aFormsD*344 4.$et!y-ame* (rim*aFormsD*C44 4.close '-, +F '-, A!

5orm documents that lie in a directory are entered into the +dditional ?n ormation ield as directory/ orm. This must be con*erted to' HHHBetBJN)*e("D%/e7t-/J")HBetBJN)*e(""-/*").

)emoving distracting elements from forms


Toolbars ha*e no unction in orms. They are more li,ely to irritate the normal user) as the orm is not being edited while data is input. These macros allow toolbars to be remo*ed and subse@uently reinstated. /owe*er) depending on the %ibre: ice *ersion) menu bars in te6t orm can only be temporarily remo*ed and then reappear.
ub (oolbar_remove ,+M oFrame A O!L'&( ,+M o)ayoutM%$ A O!L'&( oFrame E this&ompo%e%t.&urre%t&o%troller.Frame o)ayoutM%$ E oFrame.)ayoutMa%a$er o)ayoutM%$.visible E <alse o)ayoutM%$.show'leme%t*"privateMResource/me%ubar/me%ubar"4 '%d ub ub (oolbar_restore ,+M oFrame A O!L'&( ,+M o)ayoutM%$ A O!L'&( oFrame E this&ompo%e%t.&urre%t&o%troller.Frame o)ayoutM%$ E oFrame.)ayoutMa%a$er o)ayoutM%$.visible E true '%d ub

7hen a toolbar is remo*ed) all bars are a ected. /owe*er as soon as a orm control is clic,ed) the menu bar reappears. This is a sa ety precaution so that the user does not end up in a Ram. To pre*ent constant toggling) the menu bar reappears.

#atabase tasks e/panded using macros


-aking a connection to a database
o,ata ource Y (his&ompo%e%t..are%t.,ata ource +F -O( o,ata ource.+s.asswordReTuired (1'o&o%%ectio% Y o,ata ource.8et&o%%ectio%*"""""4

/ere it would be possible to pro*ide a username and a password) i one were necessary. ?n that case the brac,ets would contain &W#sernameW)W$asswordW(. ?nstead o including the username and a password in clear te6t) the dialog or password protection is called up'
') ' oAuthe%ticatio% E createA%o ervice*"com.su%.star.sdb.+%teractio%1a%dler"4 o&o%%ectio% E o,ata ource.&o%%ect@ith&ompletio%*oAuthe%ticatio%4 '-, +F

? howe*er a orm within the same 9ase ile is accessing the database) you only need'
o,ata ource E (his&ompo%e%t..are%t.&urre%t&o%troller 88# Base Handbook

+F -O( *o,ata ource.is&o%%ected*44 (he% o,ata ource.co%%ect*4 '%d +F o&o%%ectio% Y o,ata ource.Active&o%%ectio%*4

/ere the database is ,nown so a username and a password are not necessary) as these are already switched o in the basic /.D%29 con iguration or internal *ersion. 5or orms outside 9ase) the connection is made through the irst orm'
o,ata ource E (hiscompo%e%t.,rawpa$e.Forms*34 o&o%%ectio% E o,ata ource.active&o%%ectio%

?ecuring your database


?t can sometimes happen) especially when a database is being created) that the :29 ile is une6pectedly truncated. 5re@uent sa*ing a ter editing is there ore use ul) especially when using the 1eports module. 7hen the database is in use) it can be damaged by operating system ailure) i this occurs Rust as the 9ase ile is being terminated. This is when the content o the database is being written into the ile. ?n addition) there are the usual suspects or iles that suddenly re use to open) such as hard dri*e ailure. ?t does no harm there ore to ha*e a bac,up copy which is as upGtoGdate as possible. The state o the data does not change as long as the :29 ile remains open. 5or this reason) sa ety subroutines can be directly lin,ed to the opening o the ile. You simply copy the ile using the bac,up path gi*en in $ools 5 4ptions 5 +ibre4ffice 5 Paths. This macro begins to o*erwrite the oldest *ersion a ter i*e copies ha*e been made.
A! ,atabasebacKup R'M (he database <ile I.odb is copied i%to the !acKup directory. R'M (he maximum %umber o< copies is set to 2. A<ter that" the oldest copy is replaced. R'M (his method does %ot coverM R'M F data e%try i%to a database that is already ope% as the data are writte% i%to the I.odb <ile o%ly whe% it is closed. ,+M o.ath A O!L'&( ,+M o,oc A O!L'&( ,+M s(itle A (R+-8 ,+M sArl_e%d A (R+-8 ,+M sArl_start A (R+-8 ,+M i A +-('8'R ,+M K A +-('8'R o,oc E (his&ompo%e%t s(itle E o,oc.(itle sArl_start E o,oc.AR) o.ath E createA%o ervice*"com.su%.star.util..ath etti%$s"4 FOR i E C (O V +F -O( File'xists*o.ath.!acKup X "/" X i X "_" X s(itle4 (1'+F i = 2 (1'FOR K E C (O N +F File,ate(ime*o.ath.!acKup X "/" X K X "_" X s(itle4 ;E File,ate(ime*o.ath.!acKup X "/" X KHC X "_" X s(itle4 (1'i E K ':+( FOR '-, +F -':( '-, +F ':+( FOR '-, +F 3hapter , ;acros 889

-':( sArl_e%d Y o.ath.!acKup X W/W X i XWLW X s(itle File&opy*sArl_start)sArl_e%d4 '-, A!

You can also do a bac,up while 9ase is running) pro*ided that the data can be written bac, out o the cache into the ile be ore the 2atabasebac,up subroutine is carried out. ?t might be use ul to do this) perhaps a ter a speci ic elapsed time or when an onGscreen button is pressed. This cacheG clearing is handled by the ollowing subroutine'
A! @rite_data_out_o<_cache R'M @rites the data out o< the table directly to disK while !ase is ru%%i%$. ,+M o,ata A O!L'&( ,+M o,ata ource A O!L'&( o,ata E (his,atabase,ocume%t.&urre%t&o%troller +F -O( * o,ata.is&o%%ected*4 4 (1'- o,ata.co%%ect*4 o,ata ource E o,ata.,ata ource o,ata ource.<lush '-, A!

#atabase compaction
This is simply a .D% command & HUTDO!N COMPACT() which should be carried out now and again) especially a ter a lot o data has been deleted. The database stores new data) but still reser*es the space or the deleted data. ?n cases where the data ha*e been substantially altered) you there ore need to compact the database. :nce compaction is carried out) the tables are no longer accessible. The ile must be reopened. There ore this macro closes the orm rom which it is called. #n ortunately you cannot close the document itsel without causing a reco*ery when it is opened again. There ore this unction is commented out.
A! ,atabase_compactio% ,+M stMessa$e A (R+-8 o,ata ource E (his&ompo%e%t..are%t.&urre%t&o%troller G Accessible <rom the <orm +F -O( *o,ata ource.is&o%%ected*44 (1'o,ata ource.co%%ect*4 '-, +F o&o%%ectio% E o,ata ource.Active&o%%ectio%*4 o B)_ tateme%t E o&o%%ectio%.create tateme%t*4 st Tl E " 1A(,O@- &OM.A&(" G (he database is bei%$ compacted a%d shut dow% o B)_ tateme%t.executeBuery*st Tl4 stMessa$e E "(he database is bei%$ compacted." H &1R*CR4 H "(he <orm will %ow close." stMessa$e E stMessa$e H &1R*CR4 H "Followi%$ this" the database <ile should be closed." stMessa$e E stMessa$e H &1R*CR4 H "(he database ca% o%ly be accessed a<ter reope%i%$ the database <ile." ms$box stMessa$e (his,atabase,ocume%t.Form,ocume%ts.$et!y-ame* "Mai%te%a%ce" 4.close R'M (he closi%$ o< the database <ile causes a recovery operatio% whe% you ope% it a$ai%. G (his,atabase,ocume%t.close*(rue4 '-, A!

#ecreasing the table inde/ for autovalue fields


? a lot o data is deleted rom a table) users are o ten concerned that the se@uence o automatically generated primary ,eys simply continues upwards instead o starting again at the highest current
88) Base Handbook

*alue o the ,ey. The ollowing subroutine reads the currently highest *alue o the W?2W ield in a table and sets the ne6t initial ,ey *alue 1 higher than this ma6imum. ? the primary ,ey ield is not called ?2) the macro must be edited accordingly.
A! (able_i%dex_dow%*st(able A (R+-84 R'M (his subrouti%e sets the automatically i%creme%ti%$ primary Key <ield mit the preset %ame o< "+," to the lowest possible value. ,+M i%&ou%t A +-('8'R ,+M i% eTue%ce_0alue A +-('8'R o,ata ource E (his&ompo%e%t..are%t.&urre%t&o%troller G Accessible throu$h the <orm +F -O( *o,ata ource.is&o%%ected*44 (1'o,ata ource.co%%ect*4 '-, +F o&o%%ectio% E o,ata ource.Active&o%%ectio%*4 o B)_ tateme%t E o&o%%ectio%.create tateme%t*4 st Tl E " ')'&( MA:*""+,""4 FROM """Hst(ableH"""" G (he hi$hest value i% "+," is determi%ed oBuery_result E o B)_ tateme%t.executeBuery*st Tl4G Buery is lau%ched a%d the retur% value stored i% the variable oBuery_result +F -O( + -A))*oBuery_result4 (1'@1+)' oBuery_result.%ext i%&ou%t E oBuery_result.$et+%t*C4 G First data <ield is read @'-, G %ext record" i% this case %o%e as o%ly o%e record exists +F i%&ou%t E "" (1'G +< the hi$hest value is %ot a value" mea%i%$ the table is empty" the hi$hest value is set to FC i%&ou%t E FC '-, +F i% eTue%ce_0alue E i%&ou%tHC G (he hi$hrst value is i%creased by C R'M A %ew comma%d is prepared <or the database. (he +, will start a<resh <rom i%&ou%tHC. R'M (his stateme%t has %o retur% value" as %o record is bei%$ read o B)_stateme%t E o&o%%ectio%.create tateme%t*4 o B)_stateme%t.executeBuery*"A)('R (A!)' """ H st(able H """ A)('R &O)AM- ""+,"" R' (AR( @+(1 " H i% eTue%ce_0alue H ""4 '-, +F '-, A!

#ialogs
?nput errors in ields are o ten only noticed later. : ten it is necessary to modi y identical entries in se*eral records at the same time. ?t is aw,ward to ha*e to do this in normal table *iew) especially when se*eral records must be edited) as each record re@uires an indi*idual entry to be made. 5orms can use macros to do this ,ind o thing) but to do it or se*eral tables) you would need identically constructed orms. 2ialogs can do the Rob. + dialog can be supplied at the beginning with the necessary data or appropriate tables and can be called up by se*eral di erent orms.

3hapter , ;acros

88,

2ialogs are sa*ed along with the modules or macros. Their creation is similar to that o a orm. Very similar control ields are a*ailable. :nly the table control o orms is absent as a special entry possibility.

The appearance o dialog controls is determined by the settings or the graphical user inter ace. The dialog shown abo*e ser*es in the e6ample database to edit tables which are not used directly as the basis o a orm. .o) or e6ample) the media type is accessible only through a listbo6 &in the macro *ersion it becomes a combobo6(. ?n the macro *ersion) the ield contents can be e6panded by new content but an alteration o e6isting content is not possible. ?n the *ersion without macros) alterations are carried out using a separate table control. 7hile alterations in this case are easy to carry out without macros) it is @uite di icult to change the media type o many media at once. .uppose the ollowing types are a*ailable' W9oo,) boundW) W9oo,) hardGco*erW) W$aperbac,W and W1ing ileW. "ow it turns out) a ter the database has been in use or a long time) that more acti*e contemporaries oresaw similar additional media types or printed wor,s. The tas, o di erentiating them has become e6cessi*e. 7e there ore wish to reduce them) pre erably to a single term. 7ithout macros) the records in the media table would ha*e to be ound &using a ilter( and indi*idually altered. ? you ,now .D%) you can do it much better using a .D% command. You can change all the records in the 4edia table with a single entry. + second .D% command then remo*es the now surplus media types which no longer ha*e any lin, to the

8 7

Base Handbook

4edia table. $recisely this method is applied using this dialog=s 1eplace 7ith bo6 A only the .D% command is irst adapted to the 4edia Type table using a macro that can also edit other tables. : ten entries slip into a table which with hindsight can be changed in the orm) and so are no longer needed. ?t does no harm simply to delete such orphaned entries) but they are @uite hard to ind using the graphical user inter ace. /ere again a suitable .D% command is use ul) coupled with a delete instruction. This command or a ected tables is included in the dialog under Delete all superfluous entries. ? the dialog is to be used to carry out se*eral changes) this is indicated by the <dit multiple records chec,bo6. Then the dialog will not simply terminate when the :Q button is clic,ed. The macro code or this dialog can be seen in ull in the e6ample database. :nly e6cerpts are e6plained below.
A! (able_pur$e*o've%t A O!L'&(4

The macro should be launched by entering into the >dditional information section or the rele*ant buttons'
3M Form" CM ub<orm" DM ub ub<orm" RM &ombobox or table co%trol" NM Forei$% Key <ield i% a <orm" empty <or a table co%trol" 2M (able %ame o< auxiliary table" VM (able <ieldC o< auxiliary table" YM (able <ieldD o< auxiliary table" or ZM (able %ame o< auxiliary table <or table <ieldD

The entries in this area are listed at the beginning o the macro as comments. The numbers bound to them are trans erred and the rele*ant entry is read rom an array. The macro can edit listbo6es) which ha*e two entries) separated by "1". These two entries can also come rom di erent tables and be brought together using a @uery) as or instance in the $ostcode table) which has only the oreign ,ey ield TownL?2 or the town) re@uiring the Town table to display the names o towns.
,+M aForei$%(able*3" 3 to C4 ,+M aForei$%(ableD*3" 3 to C4

+mong the *ariables de ined at the beginning are two arrays. 7hile normal arrays can be created by the <&%t() command during e6ecution o the subroutine) twoGdimensional arrays must be de ined in ad*ance. TwoGdimensional arrays are necessary to store se*eral records rom one @uery when the @uery itsel re ers to more than one ield. The two arrays declared abo*e must be able to interpret @ueries that re er to two table ields. There ore they are de ined or two di erent contents by using 7 to ( or the second dimension.
st(a$ E o've%t. ource.Model.(a$ a(able*4 E plit*st(a$" "" "4 FOR i E )!ou%d*a(able*44 (O A!ou%d*a(able*44 a(able*i4 E trim*a(able*i44 -':(

The *ariables pro*ided are read. The se@uence is that set up in the comment abo*e. There is a ma6imum o nine entries) and you need to declare i an eighth entry or the table ield2 and a nineth entry or a second table e6ist. ? *alues are to be remo*ed rom a table) it is irst necessary to chec, that they do not e6ist as oreign ,eys in some other table. ?n simple table structures a gi*en table will ha*e only one oreign ,ey connection to another table. /owe*er) in the gi*en e6ample database) there is a Town table which is used or both the place o publication o media and the town or addresses. Thus the primary ,ey o the Town table is entered twice into di erent tables. These tables and oreign ,ey names can naturally also be entered using the +dditional ?n ormation ield. ?t would be nicer though i they could be pro*ided uni*ersally or all cases. This can be done using the ollowing @uery.
st Tl E " ')'&( ""F#(A!)'_-AM'""" ""F#&O)AM-_-AM'"" FROM ""+-FORMA(+O-_ &1'MA""."" / ('M_&RO R'F'R'-&'"" @1'R' "".#(A!)'_-AM'"" E G" H a(able*24 H "G"

?n the database) the ?"5:14+T?:"L.C/F4+ area contains all in ormation about the tables o the database) including in ormation about oreign ,eys. The tables that contain this in ormation can be
3hapter , ;acros 8 (

accessed using W?"5:14+T?:"L.C/F4+W.W.Y.TF4LC1:..1F5F1F"CFW. QT+9%FL"+4FW gi*es the table that pro*ides its primary ,ey or the connection. 5QT+9%FL"+4F gi*es the table that uses this primary ,ey as a oreign ,ey. 5inally 5QC:%#4"L"+4F gi*es the name o the oreign ,ey ield. The table that pro*ides its primary ,ey or use as a oreign ,ey is in the pre*iously created array at position C. + the count begins with 0) the *alue is read rom the array using )T)0&e(5).
i%&ou%t E 3 stForei$%+,(abC(abD E "+," stForei$%+,(abD(abC E "+," stAuxiltable E a(able*24

9e ore the reading o the arrays begins) some de ault *alues must be set. These are the inde6 or the array in which the *alues rom the au6iliary table will be written) the de ault primary ,ey i we do not need the oreign ,ey or a second table) and the de ault au6iliary table) lin,ed to the main table) or postcode and town) the $ostcode table. 7hen two ields are lin,ed or display in a listbo6) they can) as described abo*e) come rom two di erent tables. 5or the display o $ostcode and town the @uery is' .F%FCT W$ostcodeW.W$ostcodeW ^^ = [ = ^^ WTownW.WTownW 51:4 W$ostcodeW) WTownW 7/F1F W$ostcodeW.WTownL?2W Y WTownW.W?2W The table or the irst ield &$ostcode() is lin,ed to the second table by a oreign ,ey. :nly the in ormation rom these two tables and the $ostcode and Town ields is passed to the macro. +ll primary ,eys are by de ault called ?2 in the e6ample database. The oreign ,ey o Town in $ostcode must there ore be determined using the macro. ?n the same way the macro must access each table with which the content o the listbo6 is connected by a oreign ,ey.
oBuery_result E o B)_ tateme%t.executeBuery*st Tl4 +F -O( + -A))*oBuery_result4 (1'@1+)' oBuery_result.%ext Re,im .reserve aForei$%(able*i%&ou%t"3 to C4

The array must be reshly dimensioned each time. ?n order to preser*e the e6isting contents) they are bac,ed up using &$reser*e(.
aForei$%(ables*i%&ou%t"34 E oBuery_result.$et tri%$*C4

1eading the irst ield with the name o the table which contains the oreign ,ey. The result or the $ostcode table is the +ddress table.
aForei$%(ables*i%&ou%t"C4 E oBuery_result.$et tri%$*D4

1eading the second ield with the name o the oreign ,ey ield. The result or the $ostcode table is the ield $ostcode:?2 in the +ddress table. ?n cases where a call to the subroutine includes the name o a second table) the ollowing loop is run. :nly when the name o the second table occurs as the oreign ,ey table or the irst table is the de ault entry changed. ?n our case this does not occur) as the Town table has no oreign ,ey rom the $ostcode table. The de ault entry or the au6iliary table there ore remains $ostcodeP inally the combination o postcode and town is a basis or the +ddress table) which contains a oreign ,ey rom the $ostcode table.
+F A!ou%d*a(able*44 E Z (1'+F a(able*Z4 E aForei$%(able*i%&ou%t"34 (1'stForei$%+,(abD(abC E aForei$%(able*i%&ou%t"C4 stAuxiltable E a(able*Z4 '-, +F '-, +F i%&ou%t E i%&ou%t H C

8 8

Base Handbook

+s urther *alues may need to be read in) the inde6 is incremented to redimension the arrays. Then the loop ends.
@'-, '-, +F

? ) when the subroutine is called) a second table name e6ists) the same @uery is launched or this table'
+F A!ou%d*a(able*44 E Z (1'-

?t runs identically e6cept that the loop tests whether perhaps the irst table name occurs as a oreign ,ey table name. That is the case here' the $ostcode table contains the foreign ,ey Town:?2 rom the Town table. This oreign ,ey is now assigned to the *ariable st5oreign?2Tab1Tab2) so that the relationship between the tables can be de ined.
+F a(able*24 E aForei$%(ableD*i%&ou%t"34 (1'stForei$%+,(abC(abD E aForei$%(ableD*i%&ou%t"C4 '-, +F

+ ter a ew urther settings to ensure a return to the correct orm a ter running the dialog &determining the line number o the orm) so that we can Rump bac, to that line number a ter a new read() the loop begins) which recreates the dialog when the irst action is completed but the dialog is re@uired to be ,ept open or urther actions. The setting or repetition ta,es place using the corresponding chec,bo6
,O

9e ore the dialog is launched) irst o all the content o the listbo6es is determined. Care must be ta,en i the listbo6es represent two table ields and perhaps e*en are related to two di erent tables.
+F A!ou%d*a(able*44 E V (1'-

The listbo6 relates to only one table and one ield) as the argument array ends at Table ield1 o the au6iliary table.
st Tl E " ')'&( """ H a(able*V4 H """ FROM """ H a(able*24 H """ OR,'R !/ """ H a(able*V4 H """" ') '+F A!ou%d*a(able*44 E Y (1'-

The listbo6 relates to two table ields but only one table) as the argument array ends at Table ield2 o the au6iliary table.
st Tl E " ')'&( """ H a(able*V4 H """77G = G77""" H a(able*Y4 H """ FROM """ H a(able*24 H """ OR,'R !/ """ H a(able*V4 H """" ') '

The listbo6 is based on two table ields rom two tables. This @uery corresponds to the e6ample with the postcode and the town.
st Tl E " ')'&( """ H a(able*24 H """.""" H a(able*V4 H """77G = G77""" H a(able*Z4 H """.""" H a(able*Y4 H """ FROM """ H a(able*24 H """" """ H a(able*Z4 H """ @1'R' """ H a(able*Z4 H """.""" H stForei$%+,(abD(abC H """ E """ H a(able*24 H """.""" H stForei$%+,(abC(abD H """ OR,'R !/ """ H a(able*V4 H """" '-, +F

/ere we ha*e the irst e*aluation to determine the oreign ,eys. The *ariables st5oreign?2Tab2Tab1 and st5oreign?2Tab1Tab2 start with the *alue ?2. 5or st5oreign?2Tab1Tab2 e*aluation o the pre*ious @uery yields a di erent *alue) namely the *alue o Town:?2. ?n this way the pre*ious @uery construction yields e6actly the content already ormulated or postcode and town A only enhanced by sorting. "ow we must ma,e contact with the listbo6es) to supply them with the content returned by the @ueries. These listbo6es do not yet e6ist) since the dialog itsel has not yet been created. This dialog is created irst in memory) using the ollowing lines) be ore it is actually drawn on the screen.

3hapter , ;acros

,ialo$)ibraries.)oad)ibrary*" ta%dard"4 o,l$ E &reateA%o,ialo$*,ialo$)ibraries. ta%dard.,ialo$_(able_pur$e4

"e6t come the settings or the ields o the dialog. /ere) or e6ample) is the listbo6 which is to be supplied with the results o the abo*e @uery'
o&tl)istC E o,l$.8et&o%trol*")ist!oxC"4 o&tl)istC.add+tems*a&o%te%t*4"34

+ccess to the ields o the dialog is accomplished by using +etC-(t/-& with the appropriate name. ?n dialogs it is not possible or two ields to use the same name as this would create problems when e*aluating the dialog. The listbo6 is supplied with the contents o the @uery) which ha*e been stored in the array aContent&( . The listbo6 contains only the content to be displayed as a ield) so only the position 0 is illed. + ter all ields with the desired content ha*e been illed) the dialog is launched.
elect &ase o,l$.'xecute*4 &ase CG&ase C mea%s the "O#" butto% has bee% clicKed &ase 3G+< it was the "&a%cel" butto% i%Repetitio% E 3 '%d elect )OO. @1+)' i%Repetitio% E C

The dialog runs repeatedly as long as the *alue o Win1epetitionW is 1. This is set by the corresponding chec,bo6. /ere) in brie ) is the content a ter the W:QW button is clic,ed'
&ase C st+%haltC E o&tl)istC.$et elected+tem*4 GRead value <rom )istboxC ... R'M ... a%d determi%e the correspo%di%$ +,Fvalue.

The ?2 *alue o the irst listbo6 is stored in the *ariable Win%91W.


st(ext E o&tl(ext.(ext G Read the <ield value.

? the te6t ield is not empty) the entry in the te6t ield is handled. "either the listbo6 or a replacement *alue nor the chec,bo6 or deleting all orphaned records are considered. This is made clear by the act that te6t entry sets these other ields to be inacti*e.
+F st(ext ;= "" (1'-

? the te6t ield is not empty) the new *alue is written in place o the old one using the pre*iously read ?2 ield in the table. There is the possibility o two entries) as is also the case in the listbo6. The separator is 5. 5or two entries in di erent tables) two #$2+TFGcommands must be launched) which are created here simultaneously and orwarded) separated by a semicolon.
') '+F o&tl)istD.$et elected+tem*4 ;= "" (1'-

? the te6t ield is empty and the listbo6 2 contains a *alue) the *alue rom listbo6 1 must be replaced by the *alue in listbo6 2. This means that all records in the tables or which the records in the listbo6es are oreign ,eys must be chec,ed and) i necessary) written with an altered oreign ,ey.
st+%haltD E o&tl)istD.$et elected+tem*4 R'M Read value <rom listbox. R'M ,etermi%e +, <or the value o< the listbox.

The ?2 *alue o the second listbo6 is stored in the *ariable in%92. /ere too) things de*elop di erently depending on whether one or two ields are contained in the listbo6) and also on whether one or two tables are the basis o the listbo6 content. The replacement process depends on which table is de ined as the table which supplies the oreign ,ey or the main table. 5or the obo*e e6ample) this is the $ostcode table) as the $ostcodeL?2 is the oreign ,ey which is orwarded through %istbo6 1 and %istbo6 2.

8 !

Base Handbook

+F stAuxil(able E a(able*24 (1'FOR i E )!ou%d*aForei$%(ables*44 (O A!ou%d*aForei$%(ables*44

1eplacing the old ?2 *alue by the new ?2 *alue becomes problematic in n'mGrelationships) as in such cases) the same *alue can be assigned twice. That might be what you want) but it must be pre*ented when the oreign ,ey orms part o the primary ,ey. .o in the table rel:4edia:+uthor a medium cannot ha*e the same author twice because the primary ,ey is constructed rom 4edia:?2 and +uthor:?2. ?n the @uery) all ,ey ields are searched which collecti*ely ha*e the property #"?D#F or were de ined as oreign ,eys with the #"?D#F property using an inde6. .o i the oreign ,ey has the #"?D#F property and is already represented there with the desired uture in%92) that ,ey cannot be replaced.
st Tl E " ')'&( ""&O)AM-_-AM'"" FROM ""+-FORMA(+O-_ &1'MA""."" / ('M_+-,':+-FO"" @1'R' ""(A!)'_-AM'"" E G" H aForei$%(ables*i"34 H "G A-, ""-O-_A-+BA'"" E False A-, ""+-,':_-AM'"" E * ')'&( ""+-,':_-AM'"" FROM ""+-FORMA(+O-_ &1'MA""."" / ('M_+-,':+-FO"" @1'R' ""(A!)'_-AM'"" E G" H aForei$%(ables*i"34 H "G A-, ""&O)AM-_-AM'"" E G" H aForei$%(ables*i"C4 H "G4"

A "NON_UNI$UE" N ")&se A gi*es the names o columns that are #"?D#F. /owe*er not all column names are needed but only those which orm an inde6 with the oreign ,ey ield. This is handled by the .ubselect with the same table names &which contain the oreign ,ey( and the names o the oreign ,ey ields. ? now the oreign ,ey is present in the set) the ,ey *alue can only be replaced i other ields are used to de ine the corresponding inde6 as #"?D#F. You must ta,e care when carrying out replacements that the uni@ueness o the inde6 combination is not compromised.
+F aForei$%(ables*i"C4 E stField%ame (1'i%A%iTue E C ') ' Re,im .reserve a&olum%s*i%&ou%t4 a&olum%s*i%&ou%t4 E oBuery_result.$et tri%$*C4 i%&ou%t E i%&ou%t H C '-, +F

+ll column names) apart rom the ,nown column names or oreign ,ey ields as ?nde6 with the #"?D#F property) are stored in the array. +s the column name o the oreign ,ey ield also belongs to the group) it can be used to determine whether uni@ueness is to be chec,ed during data modi ication.
+F i%A%iTue E C (1'st Tl E "A.,A(' """ H aForei$%(ables*i"34 H """ A ""a"" '( """ H aForei$%(ables*i"C4 H """EG" H i%)!D H "G @1'R' """ H aForei$%(ables*i"C4 H """EG" H i%)!C H "G A-, * ')'&( &OA-(*I4 FROM """ H aForei$%(ables*i"34 H """ @1'R' """ H aForei$%(ables*i"C4 H """EG" H i%)!D H "G 4" +F i%&ou%t = 3 (1'stField$roup E Loi%*a&olum%s*4" """77 77"""4

? there are se*eral ields) apart rom the oreign ,ey ield) which together orm a =#"?D#F= inde6) they are combined here or a .D% grouping. :therwise only WaColumns&0(W appears as Wst5ieldgroupW.
stField%ame E "" FOR i%K E )!ou%d*a&olum%s*44 (O A!ou%d*a&olum%s*44 stField%ame E stField%ame H " A-, """ H a&olum%s*i%K4 H """ E ""a"".""" H a&olum%s*i%K4 H """ "

The .D% parts are combined or a correlated sub@uery.


-':( st Tl E )e<t*st Tl" )e%*st Tl4 S C4

3hapter , ;acros

8 "

The pre*ious @uery ends with a brac,et. "ow urther content is to be added to the sub@uery) so this closure must be remo*ed again. + ter that) the @uery is e6panded with the additional conditions.
st Tl E st Tl H stFeldbeUeich%u%$ H "8ROA. !/ *""" H stFeld$ruppe H """4 4 ; C" '-, +F

? the oreign ,ey has no connection with the primary ,ey or with a #"?D#F inde6) it does not matter i content is duplicated.
') ' st Tl E "A.,A(' """ H aForei$%(ables*i"34 H """ '( """ H aForei$%(ables*i"C4 H """EG" H i%)!D H "G @1'R' """ H aForei$%(ables*i"C4 H """EG" H i%)!C H "G" '-, +F o B)_ tateme%t.executeBuery*st Tl4 -':(

The update is carried out or as long as di erent connections to other tables occurP that is) as long as the current table is the source o a oreign ,ey in another table. This is the case twice o*er or the Town table' in the 4edia table and in the $ostcode table. + terwards the old *alue can be deleted rom listbo6 1) as it no longer has any connection to other tables.
st Tl E ",')'(' FROM """ H a(able*24 H """ @1'R' ""+,""EG" H i%)!C H "G" o B)_ tateme%t.executeBuery*st Tl4

?n some cases) the same method must now be carried out or a second table that has supplied data or the listbo6es. ?n our e6ample) the irst table is the $ostcode table and the second is the Town table. ? the te6t ield is empty and listbo6 2 also contains nothing) we chec, i the rele*ant chec,bo6 indicates that all surplus entries are to be deleted. This means the entries which are not bound to other tables by a oreign ,ey.
') '+F o&tl&hecKC. tate E C (1'st&o%ditio% E "" +F stAuxil(able E a(able*24 (1'FOR i E )!ou%d*aForei$%(ables*44 (O A!ou%d*aForei$%(ables*44 st&o%ditio% E st&o%ditio% H """+,"" -O( +- * ')'&( """ H aForei$%(ables*i"C4 H """ FROM """ H aForei$%(ables*i"34 H """4 A-, " -':( ') ' FOR i E )!ou%d*aForei$%(ablesD*44 (O A!ou%d*aForei$%(ablesD*44 st&o%ditio% E st&o%ditio% H """+,"" -O( +- * ')'&( """ H aForei$%(ablesD*i"C4 H """ FROM """ H aForei$%(ablesD*i"34 H """4 A-, " -':( '-, +F

The last +"2 must be remo*ed) since otherwise the delete instruction would end with +"2.
st&o%ditio% E )e<t*st&o%ditio%" )e%*st&o%ditio%4 F N4 G st Tl E ",')'(' FROM """ H stAuxil(able H """ @1'R' " H st&o%ditio% H "" o B)_ tateme%t.executeBuery*st Tl4

+s the table has already been purged once) the table inde6 can be chec,ed and optionally corrected downwards. .ee the subroutine described in one o the pre*ious sections.
(able_i%dex_dow%*stAuxil(able4

+ terwards) i necessary the listbo6 in the orm rom which the TableLpurge dialog was called can be updated. ?n some cases) the whole orm needs to be reread. 5or this purpose) the current record is determined at the beginning o the subroutine so that a ter the orm has been re reshed) the current record can be reinstated.
o,l$.e%d'xecute*4 G'%d dialo$ ...

8 #

Base Handbook

'-,

o,l$.,ispose*4 G... a%d remove <rom stora$e A!

2ialogs are terminated with the endF6ecute&( command and completely remo*ed rom memory with 2ispose&(.

3hapter , ;acros

8 9

3hapter (7 Database ;aintenance

6eneral remarks on maintaining databases


5re@uent alteration o the data in a database) in particular many deletions) has two e ects. 5irst) the database grows steadily e*en though it may not actually contain more data. .econd) the automatically created primary ,ey continues to increment regardless o what *alue or the ne6t ,ey is actually necessary. ?mportant maintenance is described in this chapter.

Compacting a database
The beha*ior o /.D%29 is to preser*e storage space or deleted records. 2atabases that are illed with test data) especially i this includes images) retain the same si0e e*en i all these records are subse@uently deleted. To ree this storage space) the database records must be rewritten &tables) table descriptions) etc(. :n the main 9ase inter ace) using $ools 5 ?(+) you can directly enter a simple command &which on ser*er databases is only a*ailable to the system administrator(' ./#T2:7" C:4$+CT The database is ta,en down and reed rom all accumulated waste space. + ter this is done) 9ase must be restarted in order to access the database.

)esetting autovalues
+ database is created) all possible unctions tested with e6amples) and corrections made until e*erything wor,s. 9y this time) on a*erage) many primary ,ey *alues will ha*e risen to o*er 100. 9ad luc, i the primary ,ey has been set to autoGincrement) as is commonplaceU ? the tables are emptied in preparation or normal usage or prior to handing the database on to another person) the primary ,ey continues to increment rom its current position instead o resetting itsel to 0ero. The ollowing .D% command) again entered using $ools 5 ?(+) lets you reset the initial *alue' A)('R (A!)' "(able_%ame" A)('R &O)AM- "+," R' (AR( @+(1 G-ew valueG This assumes that the primary ,ey ield has the name W?2W and has been de ined as an auto*alue ield. The new *alue should be the one that you want to be automatically created or the ne6t new record. .o) or e6ample) i current records go up to 4) the new *alue should be B.

(uerying database properties


+ll in ormation on the tables o the database is stored in table orm in a separate part o /.D%29. This separate area can be reached using the name W?"5:14+T?:"L.C/F4+W. The ollowing @uery can be used to ind out ield names) ield types) column si0es) and de ault *alues. /ere an e6ample is gi*en or a table named .earchtable. .F%FCT WC:%#4"L"+4FW) WTY$FL"+4FW) WC:%#4"L.?aFW) WC:%#4"L2F5W +. W2e ault ValueW 51:4 W?"5:14+T?:"L.C/F4+W.W.Y.TF4LC:%#4".W 7/F1F WT+9%FL"+4FW Y =.earchtable= :12F1 9Y W:12?"+%L$:.?T?:"W +ll special tables in /.D%29 are described in the appendi6 to this handboo,. ?n ormation on the content o these tables is most easily obtained by direct @ueries' ')'&( I FROM "+-FORMA(+O-_ &1'MA"." / ('M_.R+MAR/#'/ " The asteris, ensures that all a*ailable columns o the table are shown. The table searched or abo*e gi*es essential in ormation on the primary ,eys o the *arious tables.

8!7

Base Handbook

This in ormation is use ul abo*e all or macros. ?nstead o ha*ing to pro*ide detailed in ormation on each reshly created table or database) procedures are written to etch this in ormation directly out o the database and are there ore uni*ersally applicable. The e6ample database shows this) among other things) in one o the maintenance modules) where oreign ,eys are determined.

$esting tables for unnecessary entries


+ database consists o one or more main tables) which contain oreign ,eys rom other tables. ?n the e6ample database) these are the 4edia and +ddress tables. ?n the +ddress table the primary ,ey o the postcode occurs as a oreign ,ey. ? a person mo*es home) the address gets changed. The result may be that no oreign ,ey $ostcodeL?2 corresponding to this postcode e6ists any longer. ?n principle there ore) the postcode itsel could be deleted. /owe*er) it is not apparent during normal usage that the record is no longer needed. There are *arious ways to pre*ent this sort o problem arising.

$esting entries using relationship definition


The integrity o the data can be ensured while de ining relationships. ?n other words) you can pre*ent the deletion or alteration o ,eys rom leading to errors in the database. The ollowing dialog is accessible through $ools 5 )elationships) ollowed by a rightGclic, on the connector between two tables.

/ere the tables +ddress and .treet are considered. All specified actions apply to the Address table) which contains the oreign ,ey .treet:?2. #pdate options re er to an update o the ?2 ield in the .treet table. ? the numeric ,ey in the J.treetJ.J?2J ield is altered) W"o actionW means that the database resists this change i a J.treetJ.J?2J with that ,ey number occurs as a oreign ,ey in the +ddress table. J#pdate cascadeJ means that the ,ey number is simply carried o*er. ? the street =9urgring= in the .treet table has the ?2 =3= and is also represented in J+ddressJ.J.treet:?2J) the ?2 can be sa ely
3hapter (7 Database ;aintenance 8!(

altered) or e6ample) to =CE= A the corresponding J+ddressJ.J.treet:?2J *alues will be automatically be changed to =CE=. ? &et null is chosen) altering the ?2 ma,es W+ddressW.W.treetL?2W an empty ield. The delete options are handled similarly. 5or both options) the !#? currently does not allow the possibility &et default) as the !#? de ault settings are di erent rom those o the database. .ee Chapter 3) Tables. 2e ining relationships helps ,eep the relationships themsel*es clean) but it does not remo*e unnecessary records that pro*ide their primary ,ey as a oreign ,ey in the relationship. There may be any number o streets without corresponding addresses.

Bditing entries using forms and subforms


?n principle the whole interrelationship between tables can be displayed within orms. This is easiest o course when a table is related to only one other table. Thus in the ollowing e6ample) the author=s primary ,ey becomes the oreign ,ey in the table relL4ediaL+uthorP relL4ediaL+uthor also contains a oreign ,ey rom 4edia) so that the ollowing arrangement shows a n'mGrelationship with three orms. Fach is presented through a table. The irst igure shows that the title . hear 0ou knocking belongs to the author Dave <dmunds. There ore Dave <dmunds must not be deleted A otherwise in ormation re@uired or the media . hear 0ou knocking will be missing. /owe*er the listbo6 allows you to choose a di erent record instead o Dave <dmunds.

?n the orm there is a builtGin ilter whose acti*ation can tell you which categories are not needed in the 4edia table. ?n the case Rust described) almost all the e6ample authors are in use. :nly the <rich EUstner record can be deleted without any conse@uences or any other record in ;edia.

The ilter is hardGcoded in this case. ?t is ound in the orm properties. .uch a ilter is acti*ated automatically when the orm is launched. ?t can be switched o and on. ? it is deleted) it can be accessed again by a complete reload o the orm. This means more than Rust updating the dataP the whole orm document must be closed and then reopened.

8!8

Base Handbook

(ueries for finding orphan entries


The abo*e ilter is part o a @uery which can be used to ind orphaned entries. .F%FCT W.urnameW) W5irstnameW 51:4 W+uthorW 7/F1F W?2W ":T ?" &.F%FCT W+uthorL?2I 51:4 WrelL4ediaL+uthorW( ? a table contains oreign ,eys rom se*eral other tables) the @uery needs to be e6tended accordingly. This a ects) or e6ample) the Town table) which has oreign ,eys in both the 4edia table and the $ostcode table. There ore) records in the Town table which are to be deleted should not be re erenced in either o these tables. This is determined by the ollowing @uery' .F%FCT WTownW 51:4 WTownW 7/F1F W?2W ":T ?" &.F%FCT WTownL?2I 51:4 W4ediaW( +"2 W?2W ":T ?" &.F%FCT WTownL?2I 51:4 W$ostcodeW( :rphaned entries can then be deleted by selecting all the entries that pass the set ilter) and using the 2elete option in the conte6t menu o the record pointer) called up by rightGclic,ing.

#atabase search speed


Bffect of ;ueries
?t is Rust these @ueries) used in the pre*ious section to ilter data) that pro*e unsatis actory in regard to the ma6imum speed o searching a database. The problem is that in large databases) the sub@uery retrie*es a correspondingly large amount o data with which each single displayable record must be compared. :nly comparisons with the relationship ?" ma,e it possible to compare a single *alue with a set o *alues. The @uery ] 7/F1F W?2W ":T ?" &.F%FCT W+uthorL?2I 51:4 WrelL4ediaL+uthorW( can contain a large number o possible oreign ,eys rom the relL4ediaL+uthor table) which must irst be compared with the primary ,eys in the table +uthors or each record in that table. .uch a @uery is there ore not suitable or daily use but may be re@uired or database maintenance. 5or daily use) search unctions need to be constructed di erently so that the search or data is not e6cessi*ely long and does not damage dayGtoGday wor, with the database.

3hapter (7 Database ;aintenance

8!

Bffect of listbo/es and combobo/es


The more listbo6es that are built into a orm) and the more they contain) the longer the orm ta,es to load) since these listbo6es must be created. The better the 9ase program sets up the graphical inter ace and initially reads the listbo6 contents only partially) the less delay there will be. %istbo6es are created using @ueries) and these @ueries must be run when the orm is loaded or each listbo6. The same @uery structure or more listbo6es is better done using a common View) instead o repeatedly creating ields with the same synta6 using the stored .D% commands in the listbo6es. Views are abo*e all pre erable or e6ternal database systems) as here the ser*er runs signi icantly aster than a @uery which has to be put together by the !#? and reshly put to the ser*er. The ser*er treats Views as complete local @ueries.

8!!

Base Handbook

>ppendi1

arcodes
To be able to use the barcode print unction) the ont ea%CR.tt< must be installed. This ont is reely a*ailable. F+"13 barcodes can be created using ea%CR.tt< as ollows'
1 "umber 2 3 4 B C E < H > 10 11 12 13 14 1B N

#pper case) +Y0 9Y1 etc.

%ower case) aY0 bY1 etc.

.ee also the @uery arcode@BA91!@ttf@command in the e6ample database 4ediaLwithoutL4acros.

#ata types for the table editor


Integers
$y e
Tiny ?nteger .mall ?nteger ?nteger

O tion
T?"Y?"T .4+%%?"T ?"TF!F1

H&0L%B
T?"Y?"T .4+%%?"T ?"TF!F1 ^ ?"T

/an#e
2< Y 2BC ^ G 12< bis N 12E 21C Y CBB3C ^ G 32EC< bis N 32ECE 232 Y 42>4>CE2>C ^ G 214E4<3C4< bis N 214E4<3C4E 2C4

&tora#e s ace
1 9yte 2 9yte 4 9yte

9ig?nt

9?!?"T

9?!?"T

< 9yte

FloatingQpoint numbers
$y e
2ecimal

O tion
2FC?4+%

H&0L%B
2FC?4+%

/an#e
#nlimited) up to B0 places in the !#?) i6ed decimal point) per ect accuracy #nlimited) up to B0 places in the !#?) i6ed decimal point) per ect accuracy

&tora#e s ace
*ariable

"umber

"#4F1?C

"#4F1?C

*ariable

5loat 1eal 2ouble

5%:+T 1F+% 2:#9%F

&2:#9%F used instead( 1F+% 2:#9%F _$1FC?.?:"` ^ 5%:+T +dRustable) not e6act) 1B decimal places ma6imum < 9yte

8!#

Base Handbook

$e/t
$y e
Te6t Te6t Te6t & i6(

O tion
V+1C/+1 V+1C/+1L ?!":1FC+.F C/+1

H&0L%B
V+1C/+1 V+1C/+1L ?!":1FC+.F C/+1 ^ C/+1+CTF1

/an#e
+dRustable +dRustable) range a ects sorting +dRustable) rest o actual te6t replaced with spaces

&tora#e s ace
*ariable *ariable i6ed

4emo

%:"!V+1C/+1

%:"!V+1C/+1

*ariable

$ime
$y e
2ate Time 2ate/Time

O tion
2+TF T?4F T?4F.T+4$

H&0L%B
2+TF T?4F T?4F.T+4$ ^ 2+TFT?4F

/an#e

&tora#e s ace
4 9yte 4 9yte

+dRustable &0.C A C means with milliseconds(

< 9yte

4ther
$y e
Yes/"o 9inary ield & i6( 9inary ield ?mage

O tion
9::%F+" 9?"+1Y V+19?"+1Y %:"!V+19?"+1Y

H&0L%B
9::%F+" ^ 9?T 9?"+1Y V+19?"+1Y %:"!V+19?"+1Y

/an#e

&tora#e s ace

%i,e ?nteger %i,e ?nteger %i,e ?nteger

i6ed *ariable *ariable) intended or larger images

:T/F1

:T/F1

:T/F1 ^ :9-FCT

>ppendi1

8!9

uiltQin functions and stored procedures


9umeric
+s we are dealing here with loating point numbers) be sure to ta,e care with the settings o the ields in @ueries. 4ostly the display o decimal places is restricted) so that in some cases there may be une6pected results. 5or e6ample) column 1 might show 0.00 but actually contain 0.001) and column 2) 1000. ? column 3 is set to show Column 1 H Column 2) it would actually show 1. +9.&d( +C:.&d( +.?"&d( +T+"&d( +T+"2&a)b( 9?T+"2&a)b( 1eturns the absolute *alue o a number) remo*ing a minus sign where necessary. 1eturns the arcGcosine. 1eturns the arcGsine. 1eturns the arcGtangent. 1eturns the arcGtangent using coordinates. a is the *alue o the 6Ga6is) b the *alue o the yGa6is 9oth the binary orm o a and the binary orm o b must ha*e 1 at the same position to yield 1 in the result. 9?T+"2&3)B( yields 1P 0011 +"2 0101 Y 0001 9?T:1&a)b( Fither the binary orm o a or the binary orm o b must ha*e 1 at the same position to yield 1 in the result. 9?T+"2&3)B( yields EP 0011 :1 0101 Y 0111 CF?%?"!&d( C:.&d( C:T&d( 2F!1FF.&d( FM$&d( 5%::1&d( %:!&d( %:!10&d( 4:2&a)b( 1eturns the smallest whole number that is not smaller than d. 1eturns the cosine. 1eturns the cotangent. Con*erts radians to degrees. 1eturns ed & e' &2.E1<...( (. 1eturns the largest whole number that is not greater than d. 1eturns the natural logarithm to base e. 1eturns the logarithm to base 10. 1eturns the remainder as a whole number) in the di*ision o 2 whole numbers. 4:2&11)3( ergibt 2) weil 3H3N2Y11 $?&( $:7F1&a)b( 1+2?+".&d( 1+"2&( 1eturns g &3.141B...(. ab ) $:7F1&2)3( Y <) since 23 Y < Con*erts degrees to radians. 1eturns a random number greater than or e@ual to 0.0 and less than 1.0.
Base Handbook

8!)

1:#"2&a)b( 1:#"24+!?C&d(

1ounds a to b decimal places. .ol*es rounding problems) that arise rom using loating point numbers. 3.11G3.1G0.01 is not e6actly 0) but is shown as 0 in the !#?. 1:#"24+!?C ma,es it an actual 0ero *alue. 1eturns A1) i d is less than 0) 0 i dYY0 and 1 i d is greater than 0. 1eturns the sine o an angle in radians. 1eturns the s@uare root. 1eturns the tangent o an angle in radians. Truncates a to b decimal places. T1#"C+TF&2.3E4BC)2( Y 2.3E

.?!"&d( .?"&+( .D1T&d( T+"&+( T1#"C+TF&a)b(

$e/t
+.C??&s( 9?TL%F"!T/&str( C/+1&c( C/+1L%F"!T/&str( C:"C+T&str1)str2( =str1=^^=str2=^^=str3= or =str1=N=str2=N=str3= 2?55F1F"CF&s1)s2( 1eturns the +.C?? code o the irst letter o the string. 1eturns the length o the te6t string str in bits. 1eturns the letter corresponding to the +.C?? code c. 1eturns the length o the te6t in characters. Concatenates str1 and str2. Concatenates str1 N str2 N str3) simpler alternati*e to C:"C+T. 1eturns the sound di erence between s1 and s2. :nly a whole number is output. 0 means they sound the same. .o = or= and = our= yield 0) c,ingK and cwingK yield 1) cseeK and cseaK yield 0. Translates he6adecimal code to other characters. 1eturns a te6t string) with part o the te6t replaced. 9eginning with start) a length len is cut out o the te6t s and replaced by the te6t s2. ?".F1T&9undesbahn) 3) 4) mmel ( con*erts 9undesbahn into 9ummelbahn) where the length o the inserted te6t can be greater than that o the deleted te6t without causing any problems. .o ?".F1T&9undesbahn) 3) B) s und 9 ( yields =9us und 9ahn=. %C+.F&s( %F5T&s)count( %F"!T/&s( %:C+TF&search)s)_start`( Con*erts a string to lower case. 1eturns the irst count characters rom the beginning o the te6t s. 1eturns the length o te6t in characters. 1eturns the irst match or the term search in the te6t s. The match is gi*en as an o set number' &1Yle t) 0Ynot ound( .etting a starting point within the te6t string is optional. %T1?4&s( 1emo*es leading spaces and nonGprinting characters rom the beginning o a te6t string.

/FMT:1+7&s1( ?".F1T&s)start)len)s2(

>ppendi1

8!,

:CTFTL%F"!T/&str( 1+7T:/FM&s1( 1F$F+T&s)count( 1F$%+CF&s)replace)s2( 1?!/T&s)count( 1T1?4&s( .:#"2FM&s( .$+CF&count( .#9.T1&s)start_)len`( .#9.T1?"!&s)start_)len`( #C+.F&s( %:7F1&s( #$$F1&s(

1eturns the length o a te6t string in bytes. This corresponds to twice the length in characters. Con*erts to he6adecimals) re*erse o /FMT:1+7&(. 1epeats the te6t string s count times. 1eplaces all e6isting occurrences o replace in the te6t string s by the te6t s2. :pposite o %F5TP returns the last count characters at the end o a te6t string. 1emo*es all spaces and nonGprinting characters rom the end o a te6t string. 1eturns a 4Gcharacter code) corresponding to the sound o s A matches the unction 2?55F1F"CF&(. 1eturns count spaces. +bbre*iation or .#9.T1?"!. 1eturns the te6t s rom the start position &1Yle t(. ? length is le t out) the whole string is returned. Con*erts a string to upper case. +s %C+.F&s( +s #C+.F&s(

#ateO$ime
C#12+TF&( C#1T?4F&( 2+TF2?55&string) datetime1) datetime2( 1eturns the current date. 1eturns the current time. 2ate di erence between two datesG compares date/time *alues. The entry in string determines the units in which the di erence is returned' msYmillisecond) ssYsecond) miYminute) hhYhour) ddYday) mmYmonth) yy Y year. 9oth the long and the short orms can be used or string. 2+Y&date( 2+Y"+4F&date( 2+Y:54:"T/&date( 2+Y:57FFQ&date( 2+Y:5YF+1&date( /:#1&time( 4?"#TF&time( 1eturns the day o the month &1G31(. 1eturns the Fnglish name o the day. 1eturns the day o the month &1G31(. .ynonym or 2+Y&( 1eturns the wee,day as a number &1 represents .unday(. 1eturns the day o the year &1G3CC(. 1eturns the hour &0G23(. 1eturns the minute &0GB>(.

8"7

Base Handbook

4:"T/&date( 4:"T/"+4F&date( ":7&( D#+1TF1&date( .FC:"2&time( 7FFQ&date( YF+1&date( C#11F"TL2+TF C#11F"TLT?4F C#11F"TLT?4F.T+4$

1eturns the month &1G12(. 1eturns the Fnglish name o the month. 1eturns the current date and the current time together as a timestamp. +lternati*ely C#11F"TLT?4F.T+4$ can be used. 1eturns the @uarter o the year &1G4(. 1eturns the seconds part o the time &0GB>(. 1eturns the wee, o the year &1GB3(. 1eturns the year part o a date entry. .ynonym or C#12+TF&() .D%G.tandard) Base gives the message: >ccess is denied. .ynonym or C#1T?4F&() .D%G.tandard. .ynonym or ":7&() .D%G.tandard.

#atabase connection
F6cept or ?2F"T?TY&() which has no meaning in 9ase) all these can be carried out using #irect $L C-**)('.
2+T+9+.F&( #.F1&( C#11F"TL#.F1 ?2F"T?TY&( 1eturns the name o the database to which this connection belongs. 1eturns the username o this connection. .D% standard unction) synonym or #.F1&(. 1eturns the last *alue or an auto*alue ield) which was created in the current connection. This is used in macro coding to trans er a primary ,ey in one table to become a oreign ,ey or another table.

?ystem
?5"#%%&e6p)*alue( ? e6p is "#%%) *alue is returned) otherwise e6p. +lternati*ely as an e6tension C:+%F.CF&( can be used. F6p and *alue must ha*e the same data type. ? e6p is true) *1 is returned) otherwise *2. +lternati*ely C+.F 7/F" can be used. C+.F 7/F" wor,s better with the !#?. Con*erts term into another data type. .ynonym or C:"VF1T&(. ? e6pr1 is not "#%%) returns e6pr1) otherwise e6pr2 is chec,ed) then e6pr3 and so on. ? *1 is e@ual to *2) "#%% is returned) otherwise *1. ? *1 is e@ual to *2) *3 is returned. :therwise *4 is returned or "#%%) i there is no F%.F clause.

C+.F7/F"&e6p)*1)*2( C:"VF1T&term)type( C+.T&term +. type( C:+%F.CF&e6pr1)e6pr2) e6pr3)...( "#%%?5&*1)*2( C+.F *1 7/F" *2 T/F" *3 _F%.F *4` F"2

>ppendi1

8"(

C+.F 7/F" e6pr1 T/F" *1_7/F" e6pr2 T/F" *2` _F%.F *4` F"2 FMT1+CT &dYF+1 ^ 4:"T/ ^ 2+Y ^ /:#1 ^ 4?"#TF ^ .FC:"2e 51:4 Zdate or time[( $:.?T?:"&Zstring e6pression[ ?" Zstring e6pression[( .#9.T1?"!&Zstring e6pression[ 51:4 Znumeric e6pression[ _5:1 Znumeric e6pression[`( T1?4&_d%F+2?"! ^ T1+?%?"! ^ 9:T/e` 51:4 Zstring e6pression[(

? e6pr1 is true) *1 is returned _optionally urther conditions can be set`. :therwise *4 is returned or "#%% i there is no F%.F condition. Can replace many o the date and time unctions. 1eturns the year) the month) the day) etc. rom a date or date/time *alue.

? the irst string is contained in the second one) the o set o the irst string is gi*en) otherwise 0 is returned. Yields part o a te6t string rom the position speci ied in 51:4) optionally up to the length gi*en in 5:1.

"onGprinting special characters and spaces are remo*ed.

Information tables for 3?(+#


?nside a database) in ormation on all table properties and their connections to one another are stored in the .?'O2;>*.O?:&3H<;> area. This in ormation allows 9ase macros to be created that re@uire *ery ew arguments or their procedures. +n application is to be ound in the e6ample database in the ;aintenance moduleSthe *able:purge procedure or the control o dialogs. ?n a @uery) indi*idual pieces o in ormation and all the ields that belong can be pro*ided in the ollowing way' ')'&( I FROM [+-FORMA(+O-_ &1'MA[.[ / ('M_A)+A ' [ ?n contrast to a normal table) it is necessary here to use .?'O2;>*.O?:&3H<;> as a pre i6 to the appropriate name rom the ollowing list' / / / / / / / / / / / / / / / / / /
8"8

('M_A)+A ' ('M_A))(/.'+-FO ('M_!' (RO@+,'-(+F+'R ('M_&A&1'+-FO ('M_&A(A)O8 ('M_&1'&#_&O)AM-_A A8' ('M_&1'&#_&O- (RA+-( ('M_&1'&#_ROA(+-'_A A8' ('M_&1'&#_(A!)'_A A8' ('M_&)A .R+0+)'8' ('M_&O)AM-.R+0+)'8' ('M_&O)AM('M_&RO R'F'R'-&' ('M_+-,':+-FO ('M_.R+MAR/#'/ ('M_.RO&',AR'&O)AM('M_.RO&',AR' ('M_.RO.'R(+'
Base Handbook

/ / / / / / / / / / / / / / / / / / / / / / /

('M_ &1'MA ('M_ 'BA'-&' ('M_ ' +O-+-FO ('M_ ' +O('M_ A.'R(A!)' ('M_ A.'R(/.' ('M_(A!)'.R+0+)'8' ('M_(A!)' ('M_(A!)'(/.' ('M_(A!)'_&O- (RA+-( ('M_(':((A!)' ('M_(R+88'R&O)AM('M_(R+88'R ('M_(/.'+-FO ('M_A,(A((R+!A(' ('M_A,( ('M_A A8'_.R+0+)'8' ('M_A 'R ('M_0'R +O-&O)AM('M_0+'@ ('M_0+'@_&O)AM-_A A8' ('M_0+'@_ROA(+-'_A A8' ('M_0+'@_(A!)'_A A8'

#atabase repair for S.odb files


1egular bac,ing up o data should be standard practice when using a $C. 9ac,up copies are the simplest way to return to an e*en hal way current state or your data. /owe*er) in practice this is o ten lac,ing. ?n the case o sudden $C crashes) it can happen that open databases &internal /.D%29 databases( can no longer be opened in %ibre: ice. ?nstead) when you attempt to open the database) you are as,ed or a ilter corresponding to the ormat. The problem here is that part o the data in an open database is contained in wor,ing memory and is only temporarily copied to intermediate storage. :nly when the ile is closed is the whole database written bac, into the ile and repac,ed. To get access again to your data) you may ind the ollowing procedure help ul' 1. Create a copy o your database or the steps that ollow. 2. Try to open the copy with an archi*ing program. ?n the case o H.odb iles) we are dealing with a compressed ormat) a aip archi*e. ? the ile cannot be opened directly) try renaming it rom H.odb to H.0ip. ? that does not open it) your database is past sa*ing. 3. The ollowing olders will always be seen a ter opening a database ile in an archi*ing program'

>ppendi1

8"

4. The database ile must be decompressed. The most important in ormation) as ar as the data is concerned) are in the sub older database in the iles data and script. B. ?t may be necessary to loo, at the script ile and test it or contradictions. This step can) howe*er) be le t or the testing stage. The script ile contains abo*e all the description o the table structure. C. Create a new empty database ile and open this ile with the archi*ing program. E. 1eplace the iles data and script in the new database ile with the iles unpac,ed in step 4. <. Close the archi*ing program. ? it was necessary to rename the ile to H.0ip be ore opening it in the archi*ing program &this depends on your operating system() now rename it again to H.odb. >. :pen the database ile in %ibre: ice. You should be able to access your tables again. 10. /ow ar your @ueries) orms) and reports can be reco*ered in a similar way must be the subRect o urther testing. .ee also' http'// orum.openo ice.org/en/ orum/*iewtopic.php; Y<3OtY1E12B ? ) as described in the ollowing pages) you are using e6ternal /.D%29) there may be a urther problem with the H.odb ile connected with some %ibre: ice *ersions. ? e6ternal /.D%29 is used) the sa est way is through the hs@ldb.RarGarchi*e) which is supplied with %ibre: ice. ? a di erent archi*e is used) it can lead to the internal database suddenly becoming inaccessible. This is because %ibre: ice 3.6 has di iculty distinguishing between internal and e6ternal /.D%29 and produces warnings o an incompatibility between *ersions. ? internal databases can no longer be opened) you must use as your e6ternal database the supplied hsTldb.jar ile. ?n addition) you must e6tract rom the H.odb ile the database older. The properties ile in this case has an entry that leads to the abo*e error in %ibre: ice' versio%EC.Z.C o% li%e CC This line should be changed to' versio%EC.Z.3 + terwards the database older is put bac, into the H.odb pac,age and the database can once more be opened in %ibre: ice.

8"!

Base Handbook

Connecting a database to an e/ternal 3?(+#


?nternal /.D%29 is indistinguishable rom the e6ternal *ariant. ? ) as in the ollowing description) the initial access to the database is rom the outside) no ser*er unction is necessary. You Rust need the archi*e program which is supplied with %ibre: ice. You will ind it on the path under OprogramOclassesOhs;ldb.Uar. The use o this archi*e is the sa est solution) as you then get no *ersion problems. F6ternal /.D%29 is reely a*ailable or download at http'//hs@ldb.org/. 7hen the database is installed) the ollowing steps must be per ormed in %ibre: ice'

? the database dri*er does not lie on the -a*aG1untime path) it must be entered as a Class $ath under $ools 5 4ptions 5 <ava. The connection to the e6ternal database uses -29C. The database ile should be stored in a particular directory. This directory can be reely chosen. ?n the ollowing e6ample it is in the home older. The rest o the directory path and the name o the database are not gi*en here. ?t is important) i data in the database are to be written using the !#?) that ne6t to the database name the words "F'eC)=&t_s7.e*)Nt/=e" are written. .o' jdbcMhsTldbM<ileM/home/.ath(o,atabase/,atabase%ame5de<ault_schemaEtrue ?n the older you will ind the iles' ,atabase%ame.bacKup ,atabase%ame.data ,atabase%ame.properties ,atabase%ame.script ,atabase%ame.lo$

>ppendi1

8""

The ne6t step is to gi*e the de ault user) i nothing in the /.D%29 con iguration is to be changed'

This creates the connection and the database becomes accessible.


? an e6ternal database is edited with a *ersion o /.D%29 2.6) it can no longer be con*erted into an internal database under %ibre: ice. This is because o additional unctions which are not present in *ersion 1.<.6. This terminates the in*ocation in the case o *ersion 1.<.6 while the script ile o the database is being read in. ?n the same way an e6ternal database which has once been edited with a *ersion o the second series cannot a terwards be edited with *ersion 1.<.6) which is compatible with %ibre: ice.

Caution

8"#

Base Handbook

Changing the database connection to e/ternal 3?(+#


?nternal /.D% databases ha*e the disad*antage that data storage in*ol*es a compressed archi*e. :nly on compression are all the data inally written. This can more easily lead to data loss than when wor,ing with an e6ternal database. The ollowing section shows the steps necessary to success ully change an e6isting database rom an H.odb archi*e to an e6ternal *ersion in /.D%. 5rom a copy o the e6isting database) e6tract the database directory. Copy the contents into an arbitrary directory as described abo*e. +dd the database name to the resultant ilenames' ,atabase%ame.bacKup ,atabase%ame.data ,atabase%ame.properties ,atabase%ame.script ,atabase%ame.lo$ "ow the co%te%t.xml ile must be e6tracted rom the H.odb archi*e. #se any simple te6t editor to ind the ollowing lines' ;dbMco%%ectio%Fdata=;dbMco%%ectio%Fresource xli%KMhre<E"sdbcMembeddedMhsTldb"/=;dbMlo$i% dbMisFpasswordF reTuiredE"<alse"/=;/dbMco%%ectio%Fdata=;dbMdriverFsetti%$s/= These lines must be replaced with a connection to an e6ternal database) in this case a connection to a database with the name A%io%) in the hsTldb_data directory. ;dbMco%%ectio%Fdata=;dbMco%%ectio%Fresource xli%KMhre<E"jdbcMhsTldbM<ileM/home/robby/docume%ts/databases/hsTldb_da ta/A%io%5de<ault_schemaEtrue"/=;dbMlo$i% dbMuserF%ameE"sa" dbMisF passwordFreTuiredE"<alse"/=;/dbMco%%ectio%Fdata=;dbMdriverFsetti%$s dbMjavaFdriverFclassE"or$.hsTldb.jdbc,river"/= ? ) as described abo*e) the basic con iguration o /.D%29 was not damaged) the username and the optional password must also agree. + ter changing the code) co%te%t.xml must be put bac, into the H.odb archi*e. The database directory in the archi*e is now surplus to re@uirements. The data will in the uture be accessed through the e6ternal database.

Changing the database connection for multiQuser access


5or multiGuser access) /.D%29 must be made a*ailable o*er a ser*er. /ow the installation o the ser*er is carried out *aries depending on your operating system. 5or :pen.u.F) it is only necessary to download the appropriate pac,age and to start the ser*er centrally using Y+.T &runle*el setting(. #sers o other operating systems and other %inu6 distributions can li,ely ind suitable ad*ice on the ?nternet. ?n the home directory on the ser*er &in .u.F) OvarOlibOhs;ldb() you will ind) among other things) a directory called data) in which the database is to be iled) and a ile called server.properties) which controls the access to the databases in this directory. The ollowing lines reproduce the complete contents o this ile on my computer. ?t controls access to two databases) namely the original de ault database &which can be used as a new database( and the database that was e6tracted rom the H.odb ile. \ 1sTldb erver c<$ <ile. \ ee the Adva%ced (opics chapter o< the 1sTldb Aser 8uide. server.database.3 server.db%ame.3 server.urlid.3
>ppendi1

<ileMdata/db3 <irstdb db3Furl


8"9

server.database.C server.db%ame.C server.urlid.C server.sile%t server.trace

<ileMdata/u%io% u%io% u%io%Furl true <alse true

server.port J33C server.%o_system_exit

The database 0 is addressed with the name <irstdb) although the indi*idual iles in the data directory begin with db3. ? added my own database as ,atabase C. /ere the database name and ile begin identically. The two databases are addressed in the ollowing way' jdbcMhsTldbMhsTlM//localhost/<irstdb5de<ault_schemaEtrue user%ame sa password jdbcMhsTldbMhsTlM//localhost/u%io%5de<ault_schemaEtrue user%ame sa password The su i6 F'eC)=&t_s7.e*)Nt/=e to the #1%) which is necessary or write access using the graphical user inter ace o %ibre: ice) is permanently included. ? you actually need to wor, on the ser*er) you will want to consider i the database needs to be passwordGprotected or security reasons. "ow you can connect to the ser*er using %ibre: ice. 7ith this access data) the ser*er can be loaded on its own computer. :n a networ, with other computers) you must gi*e either the host name or the ?$ address to the ser*er) which in this case is running on my computer. F6ample' 4y computer has the ?$ 1>2.1C<.0.20 and is ,nown on the networ, by the name li%_serv. "ow suppose there is another computer to be entered or connection to the database' jdbcMhsTldbMhsTlM//CJD.CVZ.3.D3/u%io%5de<ault_schemaEtrue or' jdbcMhsTldbMhsTlM//li%_serv/u%io%5de<ault_schemaEtrue The database is now connected and we can write into it. Duic,ly) howe*er) an additional problem appears. The pre*iously automatically generated *alues are suddenly no longer incremented. 5or this purpose we need an additional setting.

8")

Base Handbook

AutoQincrementing values with e/ternal 3?(+#


To use auto*alues) di erent procedures or table con iguration are needed according to the *ersion o %ibre: ice. Common to all o them is the ollowing entry under Bdit 5 #atabase 5 Advance settings'

+dding +ENERATED BY DE"AULT A IDENTITY( TART !ITH 0) causes the unction o the automatically incrementing *alues or the primary ,ey to be set. The !#? in %ibre: ice ta,es up this command) but un ortunately pre aces the statement with NOT NULL) so that the command se@uence or /.D%29 is not readable. /ere you must ensure that /.D%29 gets sent the abo*e command so that the corresponding ield will contain the primary ,ey. ?n %ibre: ice the entry o auto*alues using the !#? is not possible or this reason. #sers o these *ersions should irst create a table with a primary ,ey ield that does not autoGincrement and then enter directly using $ools 5 ?(+' +%TF1 T+9%F WTableLnameW +%TF1 C:%#4" W?2W ?"T !F"F1+TF2 9Y 2F5+#%T +. +,'-(+(/* (AR( @+(1 34 This assumes that the primary ,ey ield has the name ?2.

9ote

>ppendi1

8",

8#7

Base Handbook

You might also like