Sei sulla pagina 1di 63

Database Management

Systems

Chapter 5
Advanced Queries

Jerry Post
Copyright © 2003
1
D Tables
A
Animal
AnimalOrder Animal AnimalID
OrderItem Name SaleAnimal
OrderID
OrderID Category
OrderDate SaleID

T
AnimalID Breed
ReceiveDate AnimalID
Cost Breed DateBorn
SupplierID SalePrice
Gender
ShippingCost Category
Registered
EmployeeID Breed
Employee Color

A
ListPrice
Supplier Customer
EmployeeID Photo
SupplierID LastName CustomerID
Name City FirstName Sale Phone
ContactName Phone FirstName
CityID SaleID

B
Phone Address LastName
ZipCode SaleDate
Address ZipCode Address
City EmployeeID
ZipCode CityID ZipCode
State CustomerID
CityID TaxPayerID CityID
AreaCode Category SalesTax
DateHired
Population1990

A
DateReleased
Population1980 Category
Country Registration SaleItem
Latitude
Longitude Merchandise SaleID
OrderItem

S
ItemID
ItemID
Merchandise PONumber Quantity
Description
Order ItemID SalePrice
QuantityOnHand
Quantity
PONumber ListPrice
Cost
OrderDate Category

E
ReceiveDate
SupplierID
EmployeeID
ShippingCost

2
D Organization
A  Harder Questions
T  Subqueries

A  Not In, LEFT JOIN


 UNION, Multiple JOIN columns, Recursive JOIN
B  Other SQL Commands
 DDL: Data Definition Language
A  DML: Data Manipulation Language
 OLAP
S  Microsoft SQL Server
 Oracle
E  Microsoft Access Crosstab

3
D Harder Questions
A  How many cats are “in-  Which customers (who
T stock” on 10/1/04?
 Which cats sold for more
bought something at least
once) did not buy anything

A than the average price?


 Which animals sold for more
between 11/1/04 and
12/31/04?

B than the average price of  Which customers who


animals in their category? bought Dogs also bought
products for Cats (at any
A
 Which animals have not
time)?
been sold?

S
E
4
D Sub-query for Calculation
A  Which cats sold for more than the average sale price of cats?
 Assume we know the average price is $170.

T  Usually we need to compute it first.


SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice
FROM Animal
A INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice>170));

B SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice


FROM Animal

A
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice>
( SELECT AVG(SalePrice)

S
FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE (Animal.Category=‘Cat’)

E
)
) );

5
Query04_13

D Query Sets (IN)


A SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemID
FROM (Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID)
INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID

T WHERE (SaleItem.ItemID In (1,2,30,32,33))


ORDER BY Customer.LastName, Customer.FirstName;

A Customer
CustomerID
Phone
Sale
SaleID
SaleDate
SaleItem
SaleID
ItemID

B
FirstName EmployeeID Quantity
LastName CustomerID SalePrice

Field LastName FirstName ItemID

A Table
Sort
Customer
Ascending
Customer
Ascending
SaleItem

S Criteria In (1,2,30,32,33)

E Or
List all customers (Name) who purchased one of the following items: 1, 2, 30, 32, 33.

6
D Using IN with a Sub-query
A  List all customers who bought items for cats.
T SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemID

A
FROM (Customer
INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID)
INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID

B
WHERE (SaleItem.ItemID In
(SELECT ItemID FROM Merchandise WHERE Category=‘Cat’)
);

A
S
E
7
Query04_14

D SubQuery (IN: Look up a Set)


A SELECT Customer.LastName, Customer.FirstName
FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID
WHERE ((Month([SaleDate])=3)) And Customer.CustomerID In

T (SELECT CustomerID
FROM Sale
WHERE (Month([SaleDate])=5) );

A Customer
CustomerID
Sale
SaleID
LastName First
Adkins Inga

B Phone
FirstName
LastName
SaleDate
EmployeeID
CustomerID
McCain
Grimes
Sam
Earl

A Field
Table
LastName
Customer
FirstName
Customer
Month(SaleDate)
Sale
CustomerID
Customer

S Sort
Criteria
Ascending Ascending
3 In (SELECT CustomerID FROM State

E
WHERE (Month(SaleDAte)=5)
Or

List all of the customers who bought something in March and who bought something in
May. (Two tests on the same data!) 8
Query04_15

D SubQuery (ANY, ALL)


A SELECT Animal.AnimalID, Name, SalePrice, ListPrice
FROM Animal

T INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID


WHERE ((SalePrice > Any

A
(SELECT 0.80*ListPrice
FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID

B
WHERE Category = ‘Cat’))
AND (Category=‘Cat’);

A  Any: value is compared to each item in the list. If it is True for any of
the items, the statement is evaluated to True.

S  All: value is compared to each item in the list. If it is True for every
item in the list, the statement is evaluated to True (much more
restrictive than any.

E
9
Query04_16

D SubQuery: NOT IN (Subtract)


A Animal SELECT Animal.AnimalID, Animal.Name, Animal.Category

T
AnimalID FROM Animal
Name WHERE (Animal.AnimalID Not In
Category
(SELECT AnimalID From SaleAnimal));
Breed

A Field AnimalID Name Category AnimalID Name Category


12 Leisha Dog

B Table
Sort
Animal Animal Animal 19
25
Gene
Vivian
Dog
Dog
34 Rhonda Dog

A Criteria Not In (SELECT AnimalID


FROM SaleAnimal) 88 Brandy Dog
181 Fish
Or

S  Which animals have not been sold?

E
 Start with list of all animals.
 Subtract out list of those who were sold.

10
D SubQuery: NOT IN (Data)
A Animal SaleAnimal

T
ID Name Category Breed ID SaleID SalePrice
2 Fish Angel 2 35 $10.80
4 Gary Dog Dalmation 4 80 $156.66
5 Fish Shark 6 27 $173.99

A 6
7
8
Rosie Cat
Eugene Cat
Miranda Dog
Oriental Shorthair
Bombay
Norfolk Terrier
7
8
10
25
4
18
$251.59
$183.38
$150.11

B
9 Fish Guppy 11 17 $148.47
10 Sherri Dog Siberian Huskie
11 Susan Dog Dalmation
12 Leisha Dog Rottweiler

A
S Which animals have not been sold?

E
11
Query04_17

D Left Outer Join


A SELECT Animal.AnimalID, Animal.Name, Animal.Category
FROM Animal LEFT JOIN SaleAnimal
ON Animal.AnimalID = SaleAnimal.AnimalID

T WHERE (SaleAnimal.SaleID Is Null);

Animal SaleAnimal AnimalID Name Category

A AnimalID
Name
Category
SaleID
AnimalID
SalePrice
12
19
25
Leisha
Gene
Vivian
Dog
Dog
Dog

B
Breed
34 Rhonda Dog
Field AnimalID SaleID Name Category 88 Brandy Dog
181 Fish
A Table
Sort
Animal SaleAnimal Animal Animal

S Criteria
Or
Is Null

 Which animals have not been sold?

E  LEFT JOIN includes all rows from left table (Animal)


 But only those from right table (SaleAnimal) that match a row in Animal.
 Rows in Animal without matching data in Sale Animal will have Null.
12
D Left Outer Join (Example)
A ID
2
Name Category
Fish
Breed
Angel
ID
2
SaleID
35
SalePrice
$10.80

T 4
5
6
Gary

Rosie
Dog
Fish
Cat
Dalmation
Shark
Oriental Shorthair
4
Null
6
80
Null
27
$156.66
Null
$173.99

A
7 Eugene Cat Bombay 7 25 $251.59
8 Miranda Dog Norfolk Terrier 8 4 $183.38
9 Fish Guppy Null Null Null
10 Sherri Dog Siberian Huskie 10 18 $150.11

B 11
12
Susan Dog
Leisha Dog
Dalmation
Rottweiler
11
Null
17
Null
$148.47
Null

A
S
E
13
D Older Syntax for Left Join
A  Which animals have not been sold?
T SELECT ALL

A FROM Animal, SaleAnimal


WHERE Animal.AnimalID *= SaleAnimal.AnimalID

B And SaleAnimal.SaleID Is Null;


Old Oracle syntax—
A note that the (+) symbol is on the reversed side.
SELECT ALL
S FROM Animal, SaleAnimal

E
WHERE Animal.AnimalID = SaleAnimal.AnimalID (+)
And SaleAnimal.SaleID Is Null;

14
Query04_18

D SubQuery for Computation


SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePrice

A FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE ((Animal.Category=‘Cat’) AND (SaleAnimal.SalePrice>

T ( SELECT AVG(SalePrice)
FROM Animal
INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID

A WHERE (Animal.Category=‘Cat’)
Animal SaleAnimal
) ) );

 Don’t know the

B
AnimalID SaleID average, so use a
Name AnimalID subquery to look it up.
Category SalePrice
 Watch parentheses.

A
Breed
Field AnimalID Name Category SalePrice
Table Animal Animal Animal SaleAnimal

S Sort
Criteria 3
Descending
> (SELECT Avg(SalePrice) FROM

E
Animal INNER JOIN SaleAnimal ON
Animal.AnimalID = SaleAnimal.AnimalID
WHERE Animal.Category = ‘Cat’)

Or
15
D Correlated Subquery
A  List the Animals that have sold for a price higher than the
average for animals in that Category.

T SELECT AnimalID, Name, Category, SalePrice


FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE (SaleAnimal.SalePrice>

A (SELECT Avg(SaleAnimal.SalePrice)
FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE (Animal.Category = Animal.Category) ) )

B
ORDER BY SaleAnimal.SalePrice DESC;

 The subquery needs to compute the average for a given


A category.
 Problem: Which category?
S  Answer: the category that matches the category from the main
part of the query.
E  Problem: How do we refer to it? Both tables are called Animal.
This query will not work yet.
16
Query04_19

D Correlated SubQuery (Avoid)


A  Match category in subquery with top level
 Rename tables (As)

T  Correlated Subquery
 Recompute subquery for every row in top level--slow!

A
 Better to compute and save Subquery, then use in join.

SELECT A1.AnimalID, A1.Name, A1.Category, SaleAnimal.SalePrice


FROM Animal As A1 INNER JOIN SaleAnimal

B ON A1.AnimalID = SaleAnimal.AnimalID
WHERE (SaleAnimal.SalePrice>
(SELECT Avg(SaleAnimal.SalePrice)

A FROM Animal As A2 INNER JOIN SaleAnimal


ON A2.AnimalID = SaleAnimal.AnimalID
WHERE (A2.Category = A1.Category) ) )

S ORDER BY SaleAnimal.SalePrice DESC;

E
List the Animals that have sold for a price higher than the average for animals in
that Category.

17
D Correlated Subquery Problem
A Animal + SaleAnimal
Category SalePrice

T Fish
Dog
$10.80
$156.66
Compute Avg: $37.78
Compute Avg: $174.20

A
Fish $19.80 Compute Avg: $37.78
Cat $173.99 Compute Avg: $169.73
Cat $251.59
Compute Avg: $169.73
B
Dog $183.38
Fish $1.80 Recompute average
Dog $150.11 for every row in the

A
Dog $148.47 main query!

 Assume small query


S  100,000 rows
 5 categories of 20,000 rows

E  100,000 * 20,000 = 1 billion rows to read!

18
D More Efficient Solution: 2 queries
A Animal + SaleAnimal
Saved Query
Category SalePrice

T Fish
Dog
$10.80
$156.66
Category AvgOfSalePrice

Bird $176.57
A
Fish $19.80
Cat $173.99 JOIN Cat $169.73
Cat $251.59 Dog $174.20
Animal.Category = Fish $37.78
B
Dog $183.38
Fish $1.80 Query1.Category Mammal $80.72
Dog $150.11 Reptile $181.83
Spider $118.16
A
Dog $148.47

S  Compute the averages once and save query


 JOIN saved query to main query
E  Two passes through table: 1 billion / 200,000 => 10,000

19
D UNION Operator
A SELECT EID, Name, Phone, Salary, ‘East’ AS Office
FROM EmployeeEast
UNION
T SELECT EID, Name, Phone, Salary, ‘West’ AS Office
FROM EmployeeWest

A EID
352
Name
Jones
Phone
3352
Salary
45,000
Office
East

B
876 Inez 8736 47,000 East
372 Stoiko 7632 38,000 East

A
890 Smythe 9803 62,000 West
361 Kim 7736 73,000 West

S 

Offices in Los Angeles and New York.
Each has an Employee table (East and West).

E Need to search data from both tables.



 Columns in the two SELECT lines must match.

20
D UNION, INTERSECT, EXCEPT
A
T A B C
List the name of any employee
who has worked for both the

A
East and West regions.

B T1 T2

SELECT EID, Name


A FROM EmployeeEast
INTERSECT

S SELECT EID, Name


FROM EmployeeWest

E
21
D Multiple JOIN Columns
A Breed
Animal
AnimalID
Name
T Category
Breed
Category
Breed

A
DateBorn
Gender
...

B SELECT *
FROM Breed INNER JOIN Animal
A ON Breed.Category = Animal.Category
AND Breed.Breed = Animal.Breed

S  Sometimes need to JOIN tables on more than one column.

E  PetStore: Category and Breed.

22
D Reflexive Join
A SQL EID
115
Employee
Name
Sanchez
... Manager
765

T
SELECT Employee.EID, 462 Miller 115
Employee.Name, 523 Hawk 115
Employee.Manager, E2.Name 765 Munoz 886

A FROM Employee INNER JOIN


Employee AS E2

B ON Employee.Manager = E2.EID
EID Name
Result
Manager Name
115 Sanchez 765 Munoz
A 462
523
Miller
Hawk
115
115
Sanchez
Sanchez

S  Need to connect a table to itself.


 Common example: Employee(EID, Name, . . ., Manager)

E  A manager is also an employee.


 Use a second copy of the table and an alias.

23
D Recursive Joins (SQL 99 and 200x)
A WITH RECURSIVE EmployeeList (EmployeeID, Title, Salary) AS
( SELECT EmployeeID, Title, 0.00
T FROM Manages WHERE Title = “CEO” -- starting level
UNION ALL
SELECT Manages.EmployeeID, Manages.Title, Manages.Salary

A FROM EmployeeList INNER JOIN Manages


ON EmployeeList.EmployeeID = Manages.ManagerID )
SELECT EmployeeID, Count(Title), Sum(Salary)

B FROM EmployeeList
GROUP BY EmployeEID ;

A List all of the employees and list everyone who reports to them.

S Not yet supported by vendors.


It provides tree spanning capabilities.

E
24
Not available in Microsoft Access. It is in SQL Server and Oracle.

D CASE Function
A Select AnimalID,
CASE
WHEN Date()-DateBorn < 90 Then “Baby”
T WHEN Date()-DateBorn >= 90
AND Date()-DateBorn < 270 Then “Young”

A WHEN Date()-DateBorn >= 270


AND Date()-DateBorn < 365 Then “Grown”
ELSE “Experienced”

B END
FROM Animal;

A  Used to change data to a different context.


 Example: Define age categories for the animals.

S  Less than 3 months


 Between 3 months and 9 months

E  Between 9 months and 1 year


 Over 1 year

25
D Inequality Join
A  AccountsReceivable
 Categorize by Days Late

T  30, 90, 120+


 Three queries?

A  New table for business rules


AR(TransactionID, CustomerID, Amount, DateDue)

B LateCategory(Category, MinDays, MaxDays, Charge, …)


Month 30 90 3%
A Quarter
Overdue
90
120
120
9999
5%
10%

S SELECT *
FROM AR INNER JOIN LateCategory

E ON ((Date() - AR.DateDue) >= LateCategory.MinDays)


AND ((Date() - AR.DateDue) < LateCategory.MaxDays)

26
D SQL SELECT
A SELECT DISTINCT Table.Column {AS alias} , . . .
FROM Table/Query
T INNER JOIN Table/Query ON T1.ColA = T2.ColB
WHERE (condition)
A GROUP BY Column
HAVING (group condition)
B ORDER BY Table.Column
{ Union second select }

A
S
E
27
D SQL Mnemonic
A
Someone SELECT
T From FROM
SQL is picky about
putting the
commands in the
A Ireland
Will
INNER JOIN
WHERE
proper sequence.
If you have to

B Grow
Horseradish and
GROUP BY
HAVING
memorize the
sequence, this
mnemonic may be
A Onions ORDER BY helpful.

S
E
28
D SQL Data Definition
A  Create Schema Authorization dbName password
T  Create Table TableName (Column Type, . . .)

A  Alter Table Table {Add, Column, Constraint, Drop}


 Drop {Table Table | Index Index On table}
B  Create Index IndexName ON Table (Column {ASC|
DESC})
A
S
E
29
D Syntax Examples
A CREATE TABLE Customer

T (CustomerID INTEGER NOT NULL,


LastName CHAR (10),

A more columns

B );

ALTER TABLE Customer

A DROP COLUMN ZipCode;

S ALTER TABLE Customer


ADD COLUMN CellPhone CHAR(15);

E
30
D Queries with “Every” Need EXISTS
A List the employees who have sold animals from every category.

T
A
B
A
S By hand: List the employees and the categories. Go through the
SaleAnimal list and check off the animals they have sold.

E
31
D Query With EXISTS
A List the Animal categories that have not been sold by an employee (#5).

T
SELECT Category
FROM Category
WHERE (Category <> "Other") And Category NOT IN

A (SELECT Animal.Category
FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal
ON Sale.SaleID = SaleAnimal.SaleID)
B ON Animal.AnimalID = SaleAnimal.AnimalID
WHERE Sale.EmployeeID = 5)

A If this query returns any rows, then the employee has not sold every animal.
So list all the employees for whom the above query returns no rows:

S SELECT EmployeeID, LastName FROM Employee


WHERE NOT EXISTS
E (above query slightly modified.)

32
D Query for Every
A SELECT Employee.EmployeeID, Employee.LastName
FROM Employee

T WHERE Not Exists


(SELECT Category
FROM Category
A WHERE (Category <> "Other") And Category NOT IN
(SELECT Animal.Category

B
FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal
ON Sale.SaleID = SaleAnimal.SaleID)
ON Animal.AnimalID = SaleAnimal.AnimalID

A );
WHERE Sale.EmployeeID = Employee.EmployeeID)

S Result: 3 Reasoner

E
33
D Simpler Query for Every
A Sometimes it is easier to use Crosstab and the Count function.

T
A
B
A
S But some systems do not have Crosstab, and sometimes the

E lists would be too long. So you need to know both techniques.

34
D SQL: Foreign Key
A CREATE TABLE Order
(OrderID INTEGER NOT NULL,

T OrderDate DATE,
CustomerID INTEGER

A CONSTRAINT pkorder PRIMARY KEY (OrderID),

B CONSTRAINT fkorder FOREIGN KEY (CustomerID)


REFERENCES Customer (CustomerID)

A );
Order Customer

S
OrderID CustomerID
OrderDate LastName
CustomerID * FirstName

E Address

35
D SQL Data Manipulation Commands
A
Insert Into target (column1 . . .) VALUES (value1 . . .)
T Insert Into target (column1 . . .) SELECT . . . FROM. . .

A Delete From table WHERE condition


Update table SET Column=Value,. . . Where condition
B Note the use of the Select and Where conditions.
Synatx is the same--only learn it once.
A You can also use subqueries.

S
E
36
D Copy Old Animal Data
A INSERT INTO OldAnimals
SELECT *

T FROM Animal
WHERE AnimalID IN

A
(SELECT AnimalOrderItem.AnimalID
FROM AnimalOrder INNER JOIN AnimalOrderItem

B ON AnimalOrder.OrderID = AnimalOrderItem.OrderID
WHERE (AnimalOrder.OrderDate<’01-Jan-2004’) );

A
S
E
37
D Delete Old Animal Data
A DELETE
FROM Animal

T WHERE AnimalID IN
(SELECT AnimalOrderItem.AnimalID

A FROM AnimalOrder INNER JOIN AnimalOrderItem


ON AnimalOrder.OrderID = AnimalOrderItem.OrderID

B WHERE (AnimalOrder.OrderDate<’01-Jan-2004’) );

A
S
E
38
D Update Example
A UPDATE Animal
SET ListPrice = ListPrice*1.10
T WHERE Category = ‘Cat’ ;

A UPDATE Animal
SET ListPrice = ListPrice*1.20

B WHERE Category = ‘Dog’ ;

A  Change the ListPrice of Animals at the PetStore.


 For cats, increase the ListPrice by 10%.

S  For dogs, increase the ListPrice by 20%.


 Typically use two similar UPDATE statements.

E  With the CASE function, the statements can be combined.

39
D Quality: Building Queries
A  Break questions into smaller pieces.
 Test each query.

T  Check the SQL.


 Look at the data.
Which customers who bought Dogs
also bought products for Cats
(at any time)?
A
 Check computations
 Combine into subqueries.
 Use cut-and-paste to avoid errors.

B  Check for correlated subqueries.


 Test sample data.
Who bought dogs?
Who bought cat products?

A  Identify different cases.


 Check final query and subqueries.

S
 Verify calculations.
Dogs and cat products on the same sale.
 Test SELECT queries Dogs and cat products at different times.

E before executing
UPDATE queries.
Dogs and never any cat products.
Cat products and never any Dogs.

40
D Quality Queries: Example
A Which customers who bought Dogs also bought products for Cats?
A. Which customers bought dogs?

T B. Which customers bought cat products?


SELECT DISTINCT Animal.Category, Sale.CustomerID

A
FROM Sale INNER JOIN (Animal INNER JOIN SaleAnimal
ON Animal.AnimalID = SaleAnimal.AnimalID)
ON Sale.SaleID = SaleAnimal.SaleID

B WHERE (((Animal.Category)=‘Dog’))
AND Sale.CustomerID IN (

A SELECT DISTINCT Sale.CustomerID


FROM Sale INNER JOIN (Merchandise INNER JOIN SaleItem

S
ON Merchandise.ItemID = SaleItem.ItemID)
ON Sale.SaleID = SaleItem.SaleID
WHERE (((Merchandise.Category)=‘Cat’))

E );

41
D Programming Review: Variables
A  Integer  Double
T  2 bytes
 -32768 32767
 8 bytes
 +/- 1.79769313486232 E 308

A  Long
 4 bytes
 +/- 4.94065645841247 E-324
 Currency

B  +/- 2,147,483,648
 Single
 8 bytes
 +/- 922,337,203,685,477.5808

A  4 bytes
 +/- 3.402823 E 38
 String & String*n
 Variant

S
 +/- 1.401298 E-45  Any data type
 Global, Const, Static  Null

E
42
D Programming: Scope and Lifetime
A  Scope
 Where is the variable, and
Form
Button1
which procedures can
T access it?
 Lifetime
Button2

A  When is the variable


created, and when is it
destroyed?
Form--Module Code

B
Sub Button1_Click()
Dim i1 As Integer
i1 = 3

A Different procedures,
different variables.
End Sub
Sub Button2_Click()

S Created and destroyed


each time the button
Dim i1 As Integer
i1 = 7
End Sub

E is clicked.

43
D Programming: Global Variables
A  Wider scope and lifetime
 Created at a higher level
Form
Button1

T  Form
 Public module
Button2

A
 Accessible to any procedure Form--Module Code
in that form or module. Dim i2 As Integer
 Declare it Global to make it
B
Sub Button1_Click()
available to any procedure. i2 = 20
End Sub

A Variable is created when


form is opened. Sub Button2_Click()
Clicking Button1 sets the
S initial value.
Clicking Button2 modifies
i2 = i2 + 7
End Sub

E the value.
What if user clicks buttons in a different order?

44
D Programming: Computations
A  Standard Math
+ - * /
 String
 & Concatenation

T  \ Integer divide
 ^ Exponentiation
 Left, Right, Mid
 Trim, LTrim, RTrim

A
 (2^3 = 2*2*2 = 8)  String
 Mod  Chr, Asc
 (15 Mod 4 = 3) (12 + 3 = 15)  LCase, UCase
B “Frank” & “Rose” → “FrankRose”  InStr
 Len

A Left(“Jackson”,5) → “Jacks”
Trim(“ Maria “) → “Maria”
 StrComp
 Format

S Len(“Ramanujan”) → 9
String(5,”a”) → “aaaaa”

E InStr(“8764 Main”,” “) → 5

45
D Programming: Standard Functions
A  Numeric
T φ =30
?
 Exp, Log x = loge (e )
x

 Atn, Cos, Sin, Tan 92


Trigonometric functions
A  Sqr
 Abs
√2 = 1.414
Abs(-35) → 35

B  Sgn
 Int, Fix
Sgn(-35) → -1
Int(17.893) → 17

A
 Rnd, Randomize Rnd() → 0.198474

S
E
46
D Programming:
Standard Functions: Date/Time
A  Date, Now, Time
T  DateAdd, DateDiff
 “y”, “m”, “q” . . .
02/19/04 03/21/04

A  Firstweekday
 1=Sunday,. . .
today DateDue

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


B  Can also be used
to find number of
Fridays, between
A two dates.

S
E
47
D Programming:
Standard Functions: Variant
A  Variant
T  IsDate
 IsNumeric

A  VarType
 IsEmpty

B  IsNull

A
S
E
48
D Programming: Debug
A  Stop  Immediate Window
T 

Ctrl-Break
F5: Go
 ? or Print
 Any assignment

A 

F8: Step through
S-F8: Step over
 Any code

B  Breakpoints

A
S
E
49
D Programming:
Output: Message Box
A  MsgBox
 Message
 Icons
 vbCritical Stop sign

T
 Type  vbQuestion Question mark
 Title  vbExclamation Warning
 Types: Use Constants
A
 vbInformation Circle i
 vbOKOnly vbOKCancel
 Responses
 vbAbortRetryIgnore

B  vbYesNoCancel  vbOK vbCancel


 vbYesNo vbRetryCancel  vbAbort vbRetry
 vbIgnore
A
 Defaults
 vbDefaultButton1  vbYes vbNo
 vbDefaultButton2

S  vbDefaultButton3

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

50
D Programming:
Input: InputBox
A  InputBox
 Prompt
 Returns text or Variant
 Cancel = zero string ““
T  Title
 Default
 Positions
 Twips

A  X-Pos, Y-Pos
 Prompt
 Twentieth of inch point
 72 points

B  Cannot change box size


 Use Chr(10) & Chr(13) for
 1440 twips per inch

blank lines.
A Dim str As String

S str = InputBox(
"Enter your name:",
"Sample Input", ,
E 5000, 5000)

51
D Programming: Conditions
A  If  Conditions
T  If (Condition) Then
 statements for true
 <, <=, >, >=, =, <>
 And, Or, Not, Xor

A  Else
 statements for false
 Eqv, Imp (logic)

If (Condition1) Then
B
 End If
 IIF (Cond., True, False) statements for true
Else
A
 Select Case (expr)
 Case value statements for false
 statements
If (Condition2) Then
S  Case value2
 Case Else
statements for true
End If
E  End Select
End If

52
D Programming
 Message Box Select Example
A  Could use repeated If
statements

T  Better to use Select Case

A response = MsgBox(…) response = MsgBox(…)

B
If (response == vbYes) Then Select Case response
‘ statements for Yes Case vbYes
Else ‘ statements for Yes

A If (response == vbNo) Then


‘ statements for No
Case vbNo
‘ statements for No

S Else
‘statements for Cancel
Case vbCancel
‘ statements for Cancel
End If End Case
E End If

53
D Programming: Loops
A  Do
Initialize value
Statements

T  For … Next
 For Each
Change value
Test condition
A Do Until (x > 10) Do While (x <= 10)

B ‘ Statements
x=x+1
‘ Statements
x=x+1

A Loop Loop

Do For x = 1 to 10
S ‘ Statements ‘ Statements

E
x=x+1 Next x
Loop Until (x > 10)

54
D Programming: Loops Again
A  Do  For/Each (objects)
T  Do {While | Until}
 Exit Do (optional)
 For Each element In group
 [Exit For] (optional)

A  Loop  Next element


 With (objects)

B
 Do  With object
 Loop {While | Until}  End With

A
 For/Next
 For counter = start To end
Step increment
S  Exit For (optional)
 Next counter

E
55
D Programming
Subroutines and Functions
A  Sub name (var1 As . . ., var2, . . .)
 End Sub

T  Function fname (var1 As . . .) As datatype


 fname = … ‘ returns a specific value

A  End Function
 Variables are passed by reference

B  Changes made to the parameters in the subroutine are passed


back to the caller.

A
 Unless you use ByVal
 Changes are made to a copy of the parameter, but are not
returned to the calling program.
S
E
56
D Programming: Example Subroutine
A
T
Main program

StatusMessage “Trying to connect.”

A …
StatusMessage “Verifying access.”

B End main program

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

S
E
57
D Programming: Parameter Types
A Main
j=3

T DoSum j
… ‘ j is now equal to 8 By Reference
Changes to data in the
A Subroutine DoSum (j2 As Integer)
j2 = 8
subroutine are passed back.

End Sub
B Main

A j=3
DoSum j
… ‘ j is still equal to 3 By Value
S Subroutine DoSum (ByVal j2 As Integer)
Creates a copy of the
variable, so changes are

E
j2 = 8 not returned.
End Sub

58
D Programming
Arrays and User Types
A ◆ Arrays ◆ User defined types
T ● Dim array(sub, . . .) As
type
● Type Tname
❖ ename1 As type
A ● Dim iSorts(10) As Integer ❖ ename2 As type
End Type
◆ Specifying bounds: ●

B ● (lower To upper, . . .) ◆ Dim var1 As Tname


ReDim [Preserve] array .. var1.ename1 = . . .
A
● ◆
.
◆ var1.ename2 = . . .
● Option Base 0 | 1
S ● v 2.0 arrays less than
64KB
E
59
D Programming: Financial Functions
A Fixed payments Arrays
◆ ◆
● PV (rate, nper, pmt, fv, due) ● NPV (rate, array)
FV (rate, nper, pmt, pv, due) IRR (array, guess)

T
● ●

● IPmt (rate, per, nper, pv, fv, ● MIRR (array, finrate, re_rate)
due) ◆ Depreciation

A
● NPer (rate, pmt, pv, fv, due) ● DDB (cost, salv, life, period)
● Pmt (rate, nper, pv, fv,due) ● SLN (cost, salvage, life)
● PPmt (rate, per, nper, pv, fv,

B
● SYD (cost, salv., life, period)
due)
● Rate (nper, pmt, pv, fv, due,
guess)
A ◆ rate interest rate per period
per specific period number
S

◆ nper # of periods
◆ pv present value
fv future value
E

◆ due 0=due at end, 1=due at start

60
D Programming: Text File Input/Output
A  Open filename As # file#  ChDir, ChDirve
T 

Close # file#, Reset
Print #,Put, Write


Dir
Kill, (re)Name
A 

Spc, Tab
Get, Input #, Line Input #


Lock, Unlock
CurDir, MkDir, RmDir
B 

EOF, LOF
Seek # file#, position
A
S
E
61
D OLE: Object Linking & Embedding
A  CreateObject (class)  Example
T  “appname . objecttype”
 GetObject (file, class)
 Dim obj As Object
 set obj =

A  Methods and syntax are


CreateObject(“Word.Basic”)
 obj.Bold

B
 obj.Insert “text”
defined by the software that
 obj.SaveAs “file”
exports the object.

A
S
E
62
D DDE: Dynamic Data Exchange
A  Shell  Application must be running
T 

DDEInitiate
DDEExecute


Start a conversation/topic
Issue a command
A  DDEPoke, DDE Send
 Send data
 Place data

B  DDE, DDERequest
 Request data
 Get data

A  DDETerminate  Close the session

S
E
63

Potrebbero piacerti anche