Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data...

69
1 Jerry Post Copyright © 1998 Database Management Database Management Systems Systems Chapter 7 Calculations and Data Manipulation

Transcript of Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data...

Page 1: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

1

Jerry PostCopyright © 1998

Database Management Database Management SystemsSystems

Chapter 7

Calculations and Data

Manipulation

Page 2: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

2

DDAATTAABBAASSEE

Database Programming

Variables Computations Standard Functions Debug Output Input Conditions Loops Arrays

Data on Forms Properties Events DoCmd: Internal Commands Data Transfer Across Forms Data Lookup Programming SQL Database access programming Functions & statements grouped

by task

Page 3: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

3

DDAATTAABBAASSEE

DBMS

Programming Environment

Create code (1) In forms and reports (2) Within the query system (3) Hosted in external programs

Tables

Forms &Reports

Queries

If (Click) ThenMsgBox . . .

End If

If ( . . ) Then SELECT . . .

Else . . .UPDATE . . .

End If

C++

ExternalProgram

if (. . .) { // embed SQL SELECT …}

(1)

(2)

(3)

Page 4: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

4

DDAATTAABBAASSEE

Windows Environment Before Windows

Your code did all of the work.

Programmer In complete control.

Code ran from top to bottom.

With Windows Structure and interface are

defined by Windows standards.

Event-driven. Code is in small pieces that are called as needed, when some event occurs.

Monolithic Code

Start hereDo this routineIf (. . .) Then

print . . . End IfWait for inputMore routinesEnd here

Windows Form

On_Click

On_Change

MsgBox . . .

UPDATE . . .

Event/Trigger

Programming Appendix

Page 5: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

5

DDAATTAABBAASSEE

Data on Forms Simple assignment

[control] = value value = [control]

Naming conventions Is it a variable or a control?

Full names Forms![myform]![ctlTax]

Null values: IsNull([control]) Form Code

32.50ctlTax

Sub ComputeTaxTotal = …taxRate = ...[ctlTax] = taxRate*Total

End Sub

After Update

Page 6: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

6

DDAATTAABBAASSEE

Control Properties and Methods Set properties with code Examples

Visible/Invisible Locked/Unlocked Combo box RowSource

Methods SetFocus Undo Requery

Code examples [control].Visible = False [control].Locked = False [control].SetFocus [combo].RowSource=

“SELECT ... FROM . . .”

Employee

Sub Employee_AfterUpdate()If (Employee = “manager”) Then

[cmdSalary].Visible = True[cmdSchedule].Visible = True

Else[cmdSalary].Visible = False[cmdSchedule].Visible = False

End IfEnd Sub

Page 7: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

7

DDAATTAABBAASSEE

Transfer Data Across Forms

Full names: Forms! [formname1]! [control1]

Forms must be open Form1.Visible = True

Subforms: Forms! [formname1]! [subform].Form! [control1]

Page 8: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

8

DDAATTAABBAASSEE

Common Properties

Forms Record Source Caption Default View Menu/Scroll Bars Navigation/Selection Size/Center Pop Up/Modal/Border

Controls Name Control Source Format/Decimal/Default

Controls Input Mask Validation Rule/Text Status Bar Auto Tab/Enter Visible Enabled/Locked Tab Stop/Index Size, Position Back/Fore Color/Effects Border Font

Page 9: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

9

DDAATTAABBAASSEE

Common Events

Forms Current Before/After Insert Before/After Update Delete Before/After Del Confirm Open/Close Load/Unload Activate/Deactivate Got/Lost Focus Click/Double Click Error/Timer

Controls Before/After Update Change Enter/Exit Got/Lost Focus Click Double Click Mouse Key Down/Up/Press

Page 10: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

10

DDAATTAABBAASSEE

DoCmd: Internal Commands

See help system Common uses

FindNext FindRecord GoToControl GoToPage GoToRecord Hourglass Maximize/Minimize

OpenForm OpenQuery OpenReport Print Quit RunApp (Shell) RunSQL SetWarnings TransferDatabase TransferSpreadsheet

Page 11: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

11

DDAATTAABBAASSEE

Programming: SQL

Select Into New table

Insert Into Append rows

Update Change data

Delete Delete rows

Operate on sets of data Use String for Where Use DoCmd RunSQL

Page 12: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

12

DDAATTAABBAASSEE

Update

Changes set of values--based on Where Syntax

Update table SET col1=val1, col2=val3 Where condition

ExamplesstrSQL = “Update Order Set EstShipDate=OrderDate+3”DoCmd RunSQL strSQLstrSQL = “Update Product Set Price = Price*”strSQL = strSQL & CStr(1.0 + [ctlIncrease])strSQL = strSQL & “ Where “ & [ctlWhere]DoCmd RunSQL strSQL

Page 13: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

13

DDAATTAABBAASSEE

SQL Example: Employee Titles

Employee Table Change titles

Create a form Old title (combo) New title Command button

SQL

EID Name Phone Title2298 Adams 2253 Manager9983 Cuervo 9973 Supervisor2736 Dubai 3385 Worker

Manager

Team LeaderGoGo

UPDATE EmployeeSET Title = " Team Leader "WHERE Title = " Manager ”;

Page 14: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

14

DDAATTAABBAASSEE

SQL Example: New Titles

Sub cmdGo_AfterUpdate

Build Update command in a String, using values from OldTitle and NewTitle.

Execute the command.

End Sub

UPDATE EmployeeSET Title = "Team Leader"WHERE Title = "Manager";

Manager

Team LeaderGoGo

Page 15: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

15

DDAATTAABBAASSEE

Build the SQL Update Command

Sub cmdGo_AfterUpdateDim strSQL As String

strSQL = "UPDATE Employee SET Title = ” & txtNewTitle _& " WHERE Title = ” & cboOldTitle

End Sub

UPDATE Employee SET Title = Team LeaderWHERE Title = Manager

Problem: You need quotation marks around the titles.

strSQL:

Page 16: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

16

DDAATTAABBAASSEE

SQL Update Example

Sub cmdGo_AfterUpdateDim strSQL As String, q as Stringq = Chr(34) ‘ quotation mark

strSQL = "UPDATE Employee SET Title = " & q & [txtNewTitle] & q _& " WHERE Title = " & q & [cboOldTitle] & q & " ; "

DoCmd.SetWarnings False ‘ Turn off warningsDoCmd.RunSQL strSQL ‘ Execute the SQL commandDoCmd.SetWarnings True

End Sub

UPDATE Employee SET Title = "“Team Leader "WHERE Title = "Manager";

SQLSample

Page 17: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

17

DDAATTAABBAASSEE

Debug your Query

Page 18: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

18

DDAATTAABBAASSEE

Insert Into (1) Adds rows to a table Syntax

Insert Into table (col1, col2, …) Values (value1, value2, …

strSQL = “Insert Into [Customer] (Last, First)”strSQL = strSQL & “ Values (“ & “””” & [ctlLast] & “”””strSQL = strSQL & “,” & “””” & [ctlFirst] & “””” & “)”DoCmd RunSQL strSQL

LastName FirstName

Masi Jorge

CID Last First Phone… 938 Sosa Javier 8474

Masi Jorge

Page 19: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

19

DDAATTAABBAASSEE

Insert Into (2) Copies data rows to a second table Syntax

INSERT INTO {new table, columns} SELECT {any SQL}

Example, move all customers who have not placed orders recently. Let users define “recently” by picking the

number of days.

INSERT INTO OldCustomerSELECT * FROM CustomerWHERE CustomerID NOT IN

(SELECT CustomerIDFROM OrderWHERE (Odate > Date() - x);

SQL

Page 20: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

20

DDAATTAABBAASSEE

Code Example for Insert

Dim strSQLstrSQL = “INSERT INTO OldCustomer”strSQL = strSQL & “ SELECT * FROM Customer WHERE”strSQL = strSQL & “ CustomerID NOT IN”strSQL = strSQL & “ (SELECT CustomerID FROM Order”strSQL = strSQL & “ WHERE (Odate > Date() - “strSQL = strSQL & [txtDays] & “);”

DoCmd.RunSQL strSQL

CustomerID Name Phone7763 Juarez 99873635 Kramer 22854456 Ciaro 8474

O# C# Odate9987 3635 02-15-982275 4456 05-23-98

CustomerID Name Phone7763 Juarez 9987…

Customers who have not placed an order within some time frame.

Time frame (txtDays) is given by user.

Page 21: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

21

DDAATTAABBAASSEE

Delete Delete a set of rows that match a condition Syntax: Delete From table Where condition Cascade on Delete! Example: Move old customer data

strWhere = “CustomerID NOT IN (SELECT CustomerID FROM Order”strWhere = strWhere & “ WHERE (Odate > Date() - “ & [txtDays] & “);”

strSQL = “INSERT INTO OldCustomer”strSQL = strSQL & “ SELECT * FROM Customer WHERE “ & strWhereDoCmd.RunSQL strSQL ‘ Copy old customer data

‘ To Do: Backup the data in related tables

strSQL = “DELETE FROM Customer WHERE “ & strWhereDoCmd.RunSQL strSQL ‘ Delete from main table & cascade

Page 22: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

22

DDAATTAABBAASSEE

Data Lookup Commands: D...

Syntax D... (expr, domain, criteria)

“Column” “Table” “Where Clause”

Functions DAvg, DCount, DFirst, DLast, DMin, DMax, DStDev, DStDevP, DSum, DVar, DVarP Dlookup

Usually better to use SQL. Or to write DAO code.

V = DSum(“BalanceDue”, “Customer”,

“City=‘Chicago’”)

Column Table

Where Clause

Page 23: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

23

DDAATTAABBAASSEE

Data Access Object Programming

PurposeTrack through table or

query one row at a time.Data cursor/pointer to active

row.

Why?Performance.SQL cannot do everything.

Complex calculations.Compare multiple rows.

Year Sales1995 104,3211996 145,9981997 276,0041998 362,736

MoveNextMovePreviousMoveFirstMoveLastMove

Test for Beginning and End of File

1995 104,3211996 145,9981997 276,0041998 362,736

Page 24: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

24

DDAATTAABBAASSEE

Data Access Object Programming Containers

DBEngineWorkspacesDatabasesRecordsets

ReadWrite

DBEngine

Workspace

Database

Recordset (query)

Dim dbs As DatabaseDim rst As RecordsetSet dbs = CurrentDB()Set rst = dbs.OpenRecordset(“my query”)

Page 25: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

25

DDAATTAABBAASSEE

Set dbs = CurrentDB()strSQL = “SELECT … “Set rst = dbs.OpenRecordset(strSQL)

Do Until (rst.EOF)

Read or Write datain the current row

rst.MoveNextLooprst.Close

Choose the databaseDefine the queryOpen the query to the first row

Loop through the query

Read dataor make changes

Go to the next rowRepeatClose the query

Program Structure

Page 26: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

26

DDAATTAABBAASSEE

Problems with Multiple Users

Name SalesAlice 444,321Carl 254,998Donna 652,004Ed 411,736

Original Data

Set rst = dbs. OpenRecordset(“Data”)Value1 = rst!Sales ‘ Alice (444,321)rst.MoveNext ‘ Carl…rst.MovePrevious ‘ ??? Which row

Name SalesAlice 444,321Neal 333,229Carl 254,998Donna 652,004Ed 411,736

Modified Data

New row isadded--whilecode is running.

Page 27: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

27

DDAATTAABBAASSEE

Table Locator Commands

Move Commands .MoveNext .MovePrevious .MoveFirst .MoveLast .Move nRows

Location tests BOF EOF

Bookmarks Dim MyMark As String MyMark = rst.Bookmark

(Save position)

.Move . . . (Move somewhere else)

rst.Bookmark = MyMark (Return to mark)

bmk = rst.Bookmark

rst.MoveNext

rst.Bookmark = bmk

Saveposition

Name SalesAlice 444,321Neal 333,229Carl 254,998Donna 652,004Ed 411,736

Page 28: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

28

DDAATTAABBAASSEE

Recordset Find Commands

.FindFirst “condition” .FindLast “condition” .FindNext “condition” .FindPrevious “condition” Inefficient: Sequential search Use SQL instead

rs.NoMatch

rs.Seek Indexed One item

rst.Index = “PrimaryKey”

rst.Seek “=“, keyvalue

If (rst.NoMatch = False) Then

‘ Make changes

End If

Page 29: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

29

DDAATTAABBAASSEE

Sample Data Access CodeDim dblSum As DoubleDim dbs As DatabaseDim rst As RecordsetSet dbs = CurrentDB()Set rst = dbs.OpenRecordset(“Customer”)dblSum = 0.0Do Until (rst.EOF)

dblSum = dblSum + rst!BalanceDuerst.MoveNext

Looprst.CloseMsgBox “Total Due = “ & dblSum

Compute total ofBalanceDue.

Normally use SQL instead.

Page 30: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

30

DDAATTAABBAASSEE

Sample Code to Change Data

Dim dbs As DatabaseDim rst As RecordsetDo Until (rst.EOF)

rst.Editrst!BalanceDue = rst!BalanceDue*(1 + [PctIncrease] )rst.Updaterst.MoveNext

Looprst.Close

Add a 10% charge to the BalanceDuefor every customer. The 10% value isentered on the form by the user.

What happens if the row is already locked?

Normally use SQL instead.

Page 31: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

31

DDAATTAABBAASSEE

Error Handling Errors are events Simple code:

Display error and exit MsgBox Err.Description, ,

“Title” Resume Exit_Label

Event Options On Error Goto [label] On Error Goto 0 On Error Resume Next

Resume Options Resume Resume Next Resume labelOn Error Goto ErrSub1

Program code

ExitSub1:Exit Sub

ErrSub1:MsgBox Err.Description,,”Errors”Resume ExitSub1

Error occurs

Page 32: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

32

DDAATTAABBAASSEE

Alternate Error Handling

Sub mySubroutineOn Error Resume Next

… Set rst=dbs.OpenRecordset(“data”)If IsNull(rst) Then

… Handle the errorEnd If

Exit Sub

Error occurs,skip to next line.

Test for error,handle it.

Page 33: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

33

DDAATTAABBAASSEE

Concurrent Access Concurrent Access

Multiple users or processes changing the same data at the same time.

Final data will be wrong!

Force sequentialLockingDelayed, batch updates

Two processesReceive payment ($200)Place new order ($150)

Initial balance $800Result should be $800 -

200 + 150 = $750 Interference result is

either $600 or $950

ID BalanceJones $800

$600$950

Customers

1) Read balance 8002) Subtract pmt -2004) Save new bal. 600

3) Read balance 8005) Add order 1506) Write balance 950

Receive Payment Place New Order

Page 34: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

34

DDAATTAABBAASSEE

Deadlock

DeadlockTwo (or more) processes have

placed locks on data and are waiting for the other’s data.

Many solutionsRandom wait timeGlobal lock managerTwo-phase commit - messages

Data A Data B

1) Lock Data A3) Wait for Data B

2) Lock Data B4) Wait for Data A

Page 35: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

35

DDAATTAABBAASSEE

Lock Manager

ResourceA

ResourceB

ResourceC

ResourceD

ResourceE

Process1 Lock Wait

Process2 Wait Lock

Process3 Lock

Process4 Lock Wait

Process5 Wait

Process6 Wait Lock

Process7 Wait Wait

Page 36: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

36

DDAATTAABBAASSEE

Concurrent AccessCustomer BalanceAdams 152.35Brown 315.81Jones 115.67

Using &locked

Do until rst.EOFrst.Editrst!Balance = rst!Balance*(1.0+rate)rst.Updaterst.MoveNext

Loop

Running the program to add interest charges generates an error message.

Page 37: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

37

DDAATTAABBAASSEE

Errors and LocksOn Error Goto ErrSub1

…rst.Editrst!Balance = rst!Balance*1.10rst.Update…

ExitSub1:Exit Sub

ErrSub1:

If ( MsgBox (Err.Description, VbRetryCancel, "Error (RS)” ) = vbRetry ) Then

ResumeElse

Resume ExitSub1End If

If the table is locked,Edit will cause an error.

Let the user retry the edit or exit.To do it automatically, waitfor a random number of seconds.

Page 38: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

38

DDAATTAABBAASSEE

Post’s Picky Programming• Use a naming convention.• Use proper indentation.• Comment your work.• Avoid spaces in variable names.• Use Option Explicit.• Recompile constantly.• Use as many parentheses as possible.• Split complex conditions.• Make it easy for the user.• Use the status bar and tool tips.• All code must be subject to error trapping.• Use Retry with rst.Edit sections.• Use subroutines and functions to simplify.• Keep backup copies.• Never use a raw number--use Const.• Remember that databases can be moved.• Test applications on different hardware.•Test all calculations by hand.

Page 39: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

39

DDAATTAABBAASSEE

Comments

dblSum = 0# ' Initialize the accumulatorDo While Not rst.EOF ' Loop through the table

dblSum = dblSum + rst!Balance ' Accumulate the balancerst.MoveNext ' Move to the next row

Loop ' End the loop

' Need to compute total balance from sales' Will use a loop instead of SQL' Because some conditions will be added laterdblSum = 0#Do While Not rst.EOF

' Add condition when user provides it, for example' If this customer has more than three sales past due,' only count the three most recent (write off the older ones)dblSum = dblSum + rst!Balancerst.MoveNext

Loop

Weak comments

Useful comments

Page 40: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

40

DDAATTAABBAASSEE

Sally’s Pet StoreMain Switchboard

Employee logs in.

Buttons are presented based on the management level of the employee.

AccountingMarketingEmployees

Not availableto this employee.

Purchasing formsare accessible bythis employee.

Page 41: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

41

DDAATTAABBAASSEE

Sally’s Pet Store: Switchboard LogicEvent: EmployeeID AfterUpdateOn Error Goto ErrEIDAU

Declare variables.Lookup assigned ManagementLevel of employee.Get Management levels for each section.Make two sections of buttons invisible.If (MgtLevel > Level1) Then

Make first section of buttons visible.If (MgtLevel > Level2) Then

make second section of buttons visible.End If

End IfExitEIDAU:

Exit SubErrEIDAU:

MsgBoxResume ExitEIDAU

Page 42: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

42

DDAATTAABBAASSEE

Sally’s Pet Store: Switchboard CodePrivate Sub EmployeeID_AfterUpdate()On Error GoTo ErrEIDAU Dim varLevel, varMGTLEVEL1, varMGTLEVEL2 If Not IsNull(EmployeeID) Then varLevel = DLookup("EmployeeLevel", "Employee", _

"EmployeeID=" & [EmployeeID]) If Not IsNull(varLevel) Then varMGTLEVEL1 = DLookup("Value", "Preferences", _

"KeyID=" & """" & "MGTLEVEL1" & """") varMGTLEVEL2 = DLookup("Value", "Preferences", _

"KeyID=" & """" & "MGTLEVEL2" & """") End If End If cmdAnimalPurchase.Visible = False cmdMerchandisePurchase.Visible = False cmdInventory.Visible = False cmdAccounting.Visible = False cmdMarketing.Visible = False cmdEmployees.Visible = False

Page 43: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

43

DDAATTAABBAASSEE

Sally’s Pet Store: Switchboard Code

If (varLevel > Val(varMGTLEVEL1)) Then cmdAnimalPurchase.Visible = True cmdMerchandisePurchase.Visible = True cmdInventory.Visible = True If (varLevel > Val(varMGTLEVEL2)) Then cmdAccounting.Visible = True cmdMarketing.Visible = True cmdEmployees.Visible = True End If End If

ExitEIDAU: Exit SubErrEIDAU: MsgBox Err.Description, , "Unexpected Error (EIDAU)" Resume ExitEIDAUEnd Sub

Page 44: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

44

DDAATTAABBAASSEE

Sally’s Pet Store: Employees

Enter a ZIP code and the formtries to find a matching city.Choose a city and the ZIP codeis entered automatically.

Spin buttons can be usedto set employee level.

Page 45: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

45

DDAATTAABBAASSEE

Sally’s Pet Store: Employee Spin ButtonPrivate Sub SpinLevel_SpinDown() If IsNull(EmployeeLevel) Then EmployeeLevel = 0 Else If (EmployeeLevel > 0) Then EmployeeLevel = EmployeeLevel - 1 End If

End Sub

Private Sub SpinLevel_SpinUp() If IsNull(EmployeeLevel) Then EmployeeLevel = 1 Else If (EmployeeLevel < 255) Then EmployeeLevel = EmployeeLevel + 1 End If

End Sub

Page 46: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

46

DDAATTAABBAASSEE

Sally’s Pet Store: City

Private Sub CityID_AfterUpdate()On Error GoTo ErrCIDAU

If IsNull([ZipCode]) Then [ZipCode] = DLookup("ZipCode", "City", "CityID=" & [CityID]) End If

ExitCIDAU: Exit SubErrCIDAU: MsgBox Err.Description, , "Unexpected Error (CIDAU)" Resume ExitCIDAUEnd Sub

‘ Do not replace an existing ZipCode entry.

‘ Requires a large city table.

Page 47: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

47

DDAATTAABBAASSEE

Sally’s Pet Store: ZipCodePrivate Sub Zipcode_AfterUpdate()On Error GoTo ErrZCAU Dim strZipShort As Variant, newCityID As Variant

strZipShort = Get5DigitZipCode(ZipCode) newCityID = DLookup("CityID", "City", _

"ZipCode=" & """" & strZipShort & """") If Not IsNull(newCityID) Then [CityID] = newCityID End IfExitZCAU: Exit SubErrZCAU: MsgBox Err.Description, , "Unexpected Error (ZCAU)" Resume ExitZCAUEnd Sub

‘ City table only uses 5 digit codes.

‘ But we need to store 9 digits in ZipCode.

Page 48: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

48

DDAATTAABBAASSEE

Programming Review: Variables

Integer 2 bytes -32768 32767

Long 4 bytes +/- 2,147,483,648

Single 4 bytes +/- 3.402823 E 38 +/- 1.401298 E-45

Global, Const, Static

Double 8 bytes +/- 1.79769313486232 E 308 +/- 4.94065645841247 E-324

Currency 8 bytes +/- 922,337,203,685,477.5808

String & String*n Variant

Any data type Null

Page 49: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

49

DDAATTAABBAASSEE

Programming: Scope and Lifetime Scope

Where is the variable, and which procedures can access it?

Lifetime When is the variable

created, and when is it destroyed?

Form--Module Code

Sub Button1_Click()Dim i1 As Integeri1 = 3End Sub

Sub Button2_Click()Dim i1 As Integeri1 = 7End Sub

FormButton1Button1Button2Button2

Different procedures,different variables.Created and destroyedeach time the buttonis clicked.

Page 50: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

50

DDAATTAABBAASSEE

Programming: Global Variables Wider scope and lifetime

Created at a higher level Form Public module

Accessible to any procedure in that form or module.

Declare it Global to make it available to any procedure.

Form--Module Code

Sub Button2_Click()i2 = i2 + 7End Sub

FormButton1Button1Button2Button2

Dim i2 As Integer

Variable is created whenform is opened.Clicking Button1 sets theinitial value.Clicking Button2 modifiesthe value.What if user clicks buttons in a different order?

Sub Button1_Click()i2 = 20End Sub

Page 51: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

51

DDAATTAABBAASSEE

Programming: Computations Standard Math

+ - * / \ Integer divide ^ Exponentiation

(2^3 = 2*2*2 = 8)

Mod (15 Mod 4 = 3) (12 + 3 = 15)

String & Concatenation Left, Right, Mid Trim, LTrim, RTrim String Chr, Asc LCase, UCase InStr Len StrComp Format

“Frank” & “Rose” “FrankRose”

Left(“Jackson”,5) “Jacks”

Trim(“ Maria “) “Maria”

Len(“Ramanujan”) 9

String(5,”a”) “aaaaa”

InStr(“8764 Main”,” “) 5

Page 52: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

52

DDAATTAABBAASSEE

Programming: Standard Functions

Numeric Exp, Log Atn, Cos, Sin, Tan Sqr Abs Sgn Int, Fix Rnd, Randomize

Trigonometricfunctions

x = loge (ex)

2 = 1.414

Abs(-35) 35Sgn(-35) -1

Int(17.893) 17

Rnd() 0.198474

? =3092

Page 53: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

53

DDAATTAABBAASSEE

Programming:Standard Functions: Date/Time

Date, Now, Time DateAdd, DateDiff

“y”, “m”, “q” . . . Firstweekday 1=Sunday,. . . Can also be used

to find number of Fridays, between two dates.

today DateDue

02/19/99 03/21/99

DateDue = DateAdd(“d”, 30, Date())

Page 54: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

54

DDAATTAABBAASSEE

Programming:Standard Functions: Variant

Variant IsDate IsNumeric VarType IsEmpty IsNull

Page 55: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

55

DDAATTAABBAASSEE

Programming: Debug

Stop Ctrl-Break F5: Go F8: Step through S-F8: Step over Breakpoints

Immediate Window ? or Print Any assignment Any code

Page 56: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

56

DDAATTAABBAASSEE

Programming:Output: Message Box

MsgBox Message Type Title

Types: Use Constants vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo

vbRetryCancel

Defaults vbDefaultButton1 vbDefaultButton2 vbDefaultButton3

Icons vbCritical Stop sign vbQuestion Question mark vbExclamation Warning vbInformation Circle i

Responses vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo

MsgBox "This is a message box", vbYesNoCancel + vbInformation, "Sample Box"

Page 57: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

57

DDAATTAABBAASSEE

Programming:Input: InputBox

InputBox Prompt Title Default X-Pos, Y-Pos

Prompt Cannot change box size Use Chr(10) & Chr(13) for

blank lines.

Returns text or Variant Cancel = zero string ““ Positions

Twips Twentieth of inch point 72 points 1440 twips per inch

Dim str As Stringstr = InputBox( "Enter your name:", "Sample Input", , 5000, 5000)

Page 58: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

58

DDAATTAABBAASSEE

Programming: Conditions

If If (Condition) Then

statements for true

Else statements for false

End If

IIF (Cond., True, False) Select Case (expr)

Case value statements

Case value2 Case Else End Select

Conditions <, <=, >, >=, =, <> And, Or, Not, Xor Eqv, Imp (logic)

If (Condition1) Thenstatements for true

Elsestatements for falseIf (Condition2) Then

statements for trueEnd If

End If

Page 59: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

59

DDAATTAABBAASSEE

ProgrammingSelect Example Message Box

Could use repeated If statements

Better to use Select Case

response = MsgBox(…)If (response == vbYes) Then

‘ statements for YesElse

If (response == vbNo) Then‘ statements for No

Else ‘statements for Cancel

End IfEnd If

response = MsgBox(…) Select Case response

Case vbYes‘ statements for Yes

Case vbNo‘ statements for No

Case vbCancel‘ statements for Cancel

End Case

Page 60: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

60

DDAATTAABBAASSEE

Programming: Loops

Do For … Next For Each

Do Until (x > 10)

‘ Statements

x = x + 1

Loop

Initialize value

Statements

Change value

Test condition

Do While (x <= 10)

‘ Statements

x = x + 1

Loop

Do

‘ Statements

x = x + 1

Loop Until (x > 10)

For x = 1 to 10

‘ Statements

Next x

Page 61: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

61

DDAATTAABBAASSEE

Programming: Loops Again

Do Do {While | Until}

Exit Do (optional)

Loop

Do Loop {While | Until}

For/Next For counter = start To end

Step increment Exit For (optional)

Next counter

For/Each (objects) For Each element In group

[Exit For] (optional)

Next element

With (objects) With object End With

Page 62: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

62

DDAATTAABBAASSEE

ProgrammingSubroutines and Functions

Sub name (var1 As . . ., var2, . . .) End Sub Function fname (var1 As . . .) As datatype

fname = … ‘ returns a specific value

End Function Variables are passed by reference

Changes made to the parameters in the subroutine are passed back to the caller.

Unless you use ByVal Changes are made to a copy of the parameter, but are not

returned to the calling program.

Page 63: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

63

DDAATTAABBAASSEE

Programming: Example Subroutine

Main program…StatusMessage “Trying to connect.”…StatusMessage “Verifying access.”… End main program

Sub StatusMessage (Msg As String)‘ Display Msg, location, color

End Sub

Page 64: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

64

DDAATTAABBAASSEE

Programming: Parameter TypesMainj = 3DoSum j… ‘ j is now equal to 8

Subroutine DoSum (j2 As Integer)j2 = 8

End Sub

By ReferenceChanges to data in thesubroutine are passed back.

Mainj = 3DoSum j… ‘ j is still equal to 3

Subroutine DoSum (ByVal j2 As Integer)j2 = 8

End Sub

By ValueCreates a copy of thevariable, so changes arenot returned.

Page 65: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

65

DDAATTAABBAASSEE

ProgrammingArrays and User Types

Arrays Dim array(sub, . . .) As

type Dim iSorts(10) As Integer

Specifying bounds: (lower To upper, . . .) ReDim [Preserve] array ..

. Option Base 0 | 1 v 2.0 arrays less than

64KB

User defined types Type Tname

ename1 As type ename2 As type

End Type

Dim var1 As Tname var1.ename1 = . . . var1.ename2 = . . .

Page 66: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

66

DDAATTAABBAASSEE

Programming: Financial Functions Fixed payments

PV (rate, nper, pmt, fv, due) FV (rate, nper, pmt, pv, due) IPmt (rate, per, nper, pv, fv,

due) NPer (rate, pmt, pv, fv, due) Pmt (rate, nper, pv, fv,due) PPmt (rate, per, nper, pv, fv,

due) Rate (nper, pmt, pv, fv, due,

guess)

rate interest rate per period per specific period number nper # of periods pv present value fv future value due 0=due at end, 1=due at start

Arrays NPV (rate, array) IRR (array, guess) MIRR (array, finrate, re_rate)

Depreciation DDB (cost, salv, life, period) SLN (cost, salvage, life) SYD (cost, salv., life, period)

Page 67: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

67

DDAATTAABBAASSEE

Programming: Text File Input/Output

Open filename As # file# Close # file#, Reset Print #,Put, Write Spc, Tab Get, Input #, Line Input # EOF, LOF Seek # file#, position

ChDir, ChDirve Dir Kill, (re)Name Lock, Unlock CurDir, MkDir, RmDir

Page 68: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

68

DDAATTAABBAASSEE

DDE: Dynamic Data Exchange

Shell DDEInitiate DDEExecute DDEPoke, DDE Send

Send data

DDE, DDERequest Request data

DDETerminate

Application must be running Start a conversation/topic Issue a command Place data

Get data

Close the session

Page 69: Jerry Post Copyright © 1998 1 Database Management Systems Chapter 7 Calculations and Data Manipulation.

69

DDAATTAABBAASSEE

OLE: Object Linking & Embedding

CreateObject (class) “appname . objecttype”

GetObject (file, class)

Methods and syntax are defined by the software that exports the object.

Example Dim obj As Object set obj =

CreateObject(“Word.Basic”) obj.Bold obj.Insert “text” obj.SaveAs “file”