Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Databases

Similar presentations


Presentation on theme: "Introduction to Databases"— Presentation transcript:

1 Introduction to Databases
Visual FoxPro & SQL

2 Database (數據庫) It is a collection of organised data.
It is organised so that data can be easily accessed and managed. Example Address book Student record

3 Example - Student Record
Information to be stored: Student ID Name Sex DOB Age Remarks

4 Introduction To FoxPro
Starting up click the FoxPro icon on “Office Toolbar”. Setting up working folder SET DEFAULT TO <working_folder> Setting up the date format (i.e., mm/dd/yy) SET STRICTDATE TO 0 Shutting down type “QUIT” in the command window.

5 Data Types (數據類型) In database, data are classified into different data types. Character (字元) Numeric (數值) Date (日期) Logical (邏輯) Memo (附註)

6 Data Types (數據類型) (C)haracter (字元) Example “f00147” ‘f00147’
“Po King Wan”

7 Data Types (數據類型) (N)umeric (數值) Example -25 12 123.45

8 Data Types (數據類型) (D)ate (日期) Example {12/25/99} {04/11/00}
Note that the default date format is American, i.e., mm/dd/yy

9 Data Types (數據類型) (L)ogical (邏輯) Example .T. (True) .F. (False)

10 Data Types (數據類型) (M)emo (附註)
This is a reference link to a file with an “FPT” extension.

11 Example - Student Record
Character Information to be stored: Student ID Name Sex DOB Age Remarks Character Character Date Numeric Memo

12 Notation

13 Print Command (?) Question mark (?) is used to display result in the FoxPro window. Syntax ? <exp1>[, <exp2>[, <exp3>]…] Example ? ? “My age is”, 30

14 Unary Operators + - Example +4 - (-3) +3 + (-2) -2 + (-3) -3 - (-3)

15 Arithmetic Operators addition (+) Example 123 + 456 subtraction (-)

16 Arithmetic Operators multiplication (*) Example 8 * 9 division (/)
16 / 4

17 Arithmetic Operators exponentiation (^, **) Example 3 ^ 2 2**3

18 Arithmetic Operators modulus (%), i.e., remainder of a / b where b  0
N.B. the sign of the result depends upon the divisor (b). Example 5 % 3 = 2 -16 % 3 = 2 -5 % -3 = -2

19 Order of Precedence 1. Parentheses : “()” 2. Unary operators : “+, -”
3. Binary operators (i) exponentiation : “^” (ii) multiplication, division, modulo : “*, /, %” (iii) addition, subtraction : “+, -”

20 Date Operations Adding/subtracting days
{mm/dd/yy}  n where n = 1, 2, 3, … Example ?{12/10/99} + 12 = {12/22/99} ?{12/10/99} - 9 = {12/01/99}

21 Date Operations Finding number of days n = {mm/dd/yy} - {mm/dd/yy}
Example ?{11/22/99} - {10/29/99} = 24 ?{12/31/98} - {01/01/98} = 364 Note that we CANNOT add (+) two dates together!

22 Character/String Operators
characters concatenation (+) Example ?“Karen ” + “Kwong” = “Karen Kwong” characters concatenation (-) the trailing blanks are removed of the first string. ?“Irene ” - “Tse” = “IreneTse”

23 String Operators substring operator ($)
Usage: A $ B returns .T. if string A is contained in string B, .F. otherwise. Note that characters are case sensitive. Example ?“Chung” $ “Vincent Chung” = .T. ?“Chan” $ “Vincent Chung” = .F.

24 Relational Operators greater than (>) less than (<)
less than or equal to (<=) greater than or equal to (>=) equal to (=) not equal to (<>, !=)

25 Logical Operators NOT AND OR negates the logical value.
returns true if all the logical values are true. OR returns true if one of the logical values is true.

26 Logical Operator - NOT

27 Logical Operator - AND, OR

28 Variables (變數) variable refers to the contents in the computer memory.
each variable has a unique name. Note variable name must start with an alphabet avoid using spaces and special characters except underscore (_).

29 Variables Assignment <var_name> = <value>
e.g., myName = “Vincent” STORE <value> TO <var_name> e.g., STORE 29 TO age

30 Variables Example x = 2 y = 5 ? x + y ? y ^ x z = {12/22/99} ? z + x
{12/24/99} ? y ^ x z = {12/22/99} ? z + x

31 Variables Example x = 5 y = 10 ?x * y STORE 2 TO y ?x * y
data types mismatch, outputs error message STORE 2 TO y ?x * y STORE “Tommy” TO y ?x + y

32 Function f(x) x y 30 0.5 f(x) = sin x Example

33 Functions Character Date and Time Mathematical Logical

34 Character Functions

35 Function - LEN() returns the number of characters in a character expression Syntax: LEN(<expC>) Example ?LEN(“Raymond”) 7

36 Function - UPPER() converts character string to upper case Syntax:
UPPER(<expC>) Example ?UPPER(“Kennis Cheng”) “KENNIS CHENG”

37 Function - LOWER() converts character string to lower case Syntax:
LOWER(<expC>) Example ?LOWER(“Hang Seng”) “hang seng”

38 Function - AT() returns the numeric position of the occurence of <expC1> within <expC2>, starting from the leftmost character. Syntax: AT(<expC1>, <expC2> [, <expN>]) string to look for string to be searched no. of occurrence, default is 1

39 Function - AT() Example x = “what are you talking about?” ?AT(“a”, x)
3 6 10 ?AT(“a”, x, 2) ?AT(“you”, x) ?AT(“you”, x, 2)

40 Function - LEFT() returns the specified number of leftmost characters from a character string Syntax: LEFT(<expC>, <expN>) char. expression no. of char. copied

41 Function - LEFT() Example ?LEFT(“Ken Chan”, 3) “Ken”

42 Function - RIGHT() returns the specified number of rightmost characters from a character string Syntax: RIGHT(<expC>, <expN>) char. expression no. of char. copied

43 Function - RIGHT() Example ?RIGHT(“Ken Chan”, 4) “Chan”

44 Function - SUBSTR() returns a specified number of characters from the given character string Syntax: SUBSTR(<expC>, <expN1> [, <expN2>]) char. expression starting position no. of char. copied

45 Function - SUBSTR() Example ?SUBSTR(“Wong Ka Lun”, 6, 2)
“Tam” ?SUBSTR(“Wilson Tam”, 8) 5 x = “Chan Sze Lai” ?SUBSTR(x, AT(“ ”, x)+1) “Sze Lai”

46 Function - STUFF() returns a character string created by replacing a specified number of characters in a character string with another character string Syntax: STUFF(<expC1>, <expN1>, <expN2>, <expC2>) no. of char. to be replaced, if 0, the replacement char. is inserted into <expC1> starting pos. original char. replacement char.

47 Function - STUFF Example x = “She is smart” y = “hard-working”
?STUFF(x, 8, 5, y) “She is hard-working”

48 “This is not really hard”
Function - STUFF() Example x = “This is hard” y = “not really ” ?STUFF(x, AT(“ ”, x, 2)+1, 0, y) 8 “This is not really hard”

49 Function - STR() returns the character string equivalent to a specified numeric expression Syntax: STR(<expN1>[, <expN2>[, <expN3>]]) numeric expression length of character no. of decimal places

50 Function - STR() Example ?STR(29) ?STR(29.357, 6, 2)
“29” “ 29.36” ?STR(29.357, 6, 2) “29.4” ?STR(29.357, 4, 1)

51 Function - VAL() returns a numeric expression from a specified character string composed of numbers Syntax: VAL(<expC>)

52 Function - VAL() Example ?VAL(“29”) ?VAL(“007”) ?VAL(“A160”)
?VAL(“007”) 280 ?VAL(“A160”) ?VAL(“280T”) 2 X 103 = 2000 ?VAL(“2E3”)

53 Function - ASC() returns the ASCII code for the leftmost character in a character string. Syntax: ASC(<expC>)

54 Function - ASC() Example ?ASC(“a”) 97 65 ?ASC(“ACCURA”)

55 Function - CHR() returns the character associated with the specified numeric ASCII code Syntax: CHR(<expN>) Example ?CHR(100) “d”

56 Function - ALLTRIM() removes the leading and trailing space from the given string Syntax: ALLTRIM(<expC>) Example ?ALLTRIM(“ HSSC ”) “HSSC”

57 Function - LTRIM() removes the leading space from the given string
Syntax: LTRIM(<expC>) Example ?LTRIM(“ HSSC ”) “HSSC ”

58 Function - RTRIM() / TRIM()
removes the trailing space from the given string Syntax: RTRIM(<expC>) Example ?RTRIM(“ HSSC ”) “ HSSC”

59 Function - SPACE() returns a character string composed of a specified number of spaces Syntax: SPACE(<expN>) Example ?“Karen” + SPACE(5) + “Wong” “Karen Wong”

60 Reference Visual FoxPro & SQL - Ch2. p.38 - p.49
Practical Exercises (p.67) Ex hand-in Monday

61 Date & Time Functions

62 Function - DATE() returns the current system date Syntax: DATE()
Example ?DATE()

63 Function - TIME() returns the current system time Syntax: TIME()
Example ?TIME()

64 Function - DAY() returns the day of <expD> Syntax:
DAY(<expD>) Example ?DAY({09/01/98}) 1

65 Function - YEAR() returns the year of <expD> Syntax:
YEAR(<expD>) Example ?YEAR(DATE())

66 Function - CMONTH() returns the month of <expD> Syntax:
CMONTH(<expD>) Example ?CMONTH({02/28/00}) “February”

67 Function - MONTH() returns the numeric value of month of <expD>
Syntax: MONTH(<expD>) Example ?MONTH(DATE())

68 Function - CDOW() returns the day of week of <expD>. Syntax:
CDOW(<expD>) Example ?CDOW({09/01/98}) = “Tuesday”

69 Function - DOW() returns the numeric value of day of week of <expD>, i.e., Sunday starts from 1 Syntax: DOW(<expD>) Example ?DOW({09/01/98}) = 3

70 Function - CTOD() converts <expC> to date type Syntax:
CTOD(<expC>) Example ?CTOD(“02/28/00”) = {02/28/00}

71 Function - DTOC() converts <expD> to character type Syntax:
DTOC(<expD>) Example ?DTOC({02/12/99}) = “02/12/99”

72 Reference Visual FoxPro & SQL - Ch2. p.56 - p.59
Practical Exercise p.67 Ex. 13

73 Mathematical Functions

74 Function - ABS() returns an absolute value of <expN> Syntax:
ABS(<expN>) Example ?ABS(2) = 2 ?ABS(-12.5) = 12.5

75 Function - INT() returns an integer part of <expN> Syntax:
INT(<expN>)

76 Function - INT() Example ?INT(3.25) 3 2 -2 ?INT(2.58) ?INT(-2.5)

77 Function - ROUND() returns a numeric expression rounded to a specified number of decimal places Syntax: ROUND(<expN1>, <expN2>) number to be rounded no. of decimal places

78 Function - ROUND() Example ?ROUND(10.475, 2) = 10.48

79 Function - SQRT() returns the square root of <expN> Syntax:
SQRT(<expN>) Example ?SQRT(16) = 4

80 Function - MOD() returns the remainder of
<expN1> / <expN2> (<expN2>  0, i.e., same as % operator) Syntax: MOD(<expN1>, <expN2>)

81 Function - MOD() Example ?MOD(5, 3) = 2 ?MOD(15, 8) = 7

82 Logical Functions IIF

83 Function - IIF() returns <exp1> if <expL> is true, <exp2> otherwise. Syntax: IIF(<expL>, <exp1>, <exp2>)

84 Function - IIF() It is like: IF <expL> = True THEN <exp1>
ELSE <exp2>

85 Example IF fifth_lesson = free THEN lunch ELSE lesson

86 returns the first expression, i.e.,
Function - IIF() Since 0<3 is true, so the function returns the first expression, i.e., “It is true” Example ?IIF(0<3, “It is true”, “It is false”) ?IIF(MONTH(DATE())=2, “Feb”, “Others”)

87 More Example IF today = Sunday THEN family_day ELSE
IF today = Saturday THEN go_out_with_friend school_day

88 More Example ?IIF(CDOW(DATE())= “Sunday”, “family_day”,
IIF(CDOW(DATE()) = “Saturday”, “go_out”, “school_day”))

89 Note 0 < x < 5 FoxPro cannot read this kind of condition.
We have to write x > 0 AND x <5

90 Reference Visual FoxPro & SQL - Ch2. p.53 - p.56, p. 60
Practical Exercise p.68 Ex. 15

91 Creating A Database Data Types CREATE

92 Data Types Character (字元) Numeric (數值) Date (日期) Logical (邏輯)
Memo (附註)

93 Command - CREATE creates a new database file Syntax:
CREATE <filename>

94 Viewing/Modifying A Database Structure
LIST STRUCTURE DISPLAY STRUCTURE MODIFY STRUCTURE

95 Opening/Closing A Database File
USE CLOSE ALL

96 Command - USE opens or closes a database Syntax:
USE [<filename>] [ALIAS <name>]

97 Command - CLOSE ALL closes all opened files Syntax: CLOSE ALL

98 Viewing Database Records
LIST

99 Clearing FoxPro Screen

100 Reference Visual FoxPro & SQL - Ch4. p.94 - p.99

101 Displaying Database Records
Produce a list to show the student’s name and class name. Produce a list to show the student’s name who were born between 1981 and 1982. Produce a list to show the name of female student in class 6B.

102 Record Pointer Database File Beginning of File Record 1 . Record n
End of File

103 Status Bar Total number of records Studrec 1 / 10 Current opened
database Current record i.e., a record that the record pointer pointed to

104 Moving The Record Pointer
GO SKIP

105 Command - GO moves record pointer to a particular record Syntax:
GO [RECORD] <expN> GO <TOP | BOTTOM>

106 Example Move the record pointer to the last record. GO BOTTOM
Move the record pointer to record 6. Move the record pointer to the first record. GO TOP

107 Command - SKIP moves record pointer forward or backward Syntax:
SKIP [<expN>]

108 Example Move the record pointer to the next record. SKIP
Current Record: 2 Move the record pointer to the next record. SKIP Current Record: 5 Move the record pointer to record 5. SKIP 3 Current Record: 7 Move the record pointer 2 records forward. SKIP 2 Current Record: 3 Move the record pointer 4 records backward. SKIP -4

109 Displaying Database Records
show the current record of the current database. LIST show all the records of the current database.

110 Command - LIST shows all the records in the current database. Syntax:
LIST [[FIELDS] <field1>[, <field2>…]] [<scope>] [FOR <expL> | WHILE <expL>] [TO PRINTER | TO FILE <filename>]

111 Command - DISPLAY shows the current record of the current database.
Syntax: DISPLAY [[FIELDS] <field1>[, <field2>...]] [<scope>] [FOR <expL> | WHILE <expL>] [TO PRINTER | TO FILE <filename>]

112 Example Produce a list to show the student’s name and class name.
LIST FIELDS name, class LIST name, class

113 FOR checks the logical value of <expL> starting from the first record to the last record. returns the record only if the logical value of <expL> is TRUE.

114 Example - FOR Produce a list to show the name of student who were born between 1981 and 1982. LIST name FOR YEAR(dob) >= 1981 AND YEAR(dob) <= 1982

115 Example - FOR Produce a list to show the name of female student in class 6B. LIST name FOR sex = “F” AND class = “6B”

116 WHILE checks the logical value of <expL> starting from the current record. returns the record only if the logical value of <expL> is TRUE. stops checking when the logical value of <expL> is FALSE.

117 Example - WHILE GO TOP LIST WHILE sex = “M” GO 5 LIST WHILE sex = “F”
Current Record: 1 GO TOP LIST WHILE sex = “M” Current Record: 7 GO 5 LIST WHILE sex = “F”

118 Scope Keywords RECORD <expN> NEXT <expN> REST ALL
specifying particular record number a range of records beginning with current record a range of records beginning with current record to the last records all records

119 Example - Scope Keyword
Produce a list to show all records by using command DISPLAY. DISPLAY ALL Show record number 4 by using command LIST. LIST RECORD 4

120 Example - Scope Keyword
Starting from the current record, show the next 3 records. LIST NEXT 3 Show the rest of the records. LIST REST

121 Summary Moving Record Pointer Displaying Database Records
GO, SKIP Displaying Database Records DISPLAY, LIST Setting Criteria FOR, WHILE Scope RECORD, NEXT, REST, ALL

122 Reference Visual FoxPro & SQL, Ch. 4, p.99 - p.105
Practical Exercise p.122 Ex. 10, 12, 13, 14

123 Viewing/Modifying A Text File
TYPE MODIFY FILE

124 Command - TYPE views the contents of a text file Syntax:
TYPE <file1> [TO PRINTER | TO FILE <file2>]

125 Command - MODIFY FILE modifies the contents of a text file Syntax:
MODIFY FILE <filename>

126 Example USE studrec LIST name, dob FOR ave_mark < 60
TO FILE testing1 TYPE testing1.txt MODIFY FILE testing1.txt TYPE testing1.txt TO PRINTER Note that the extention “TXT” must be specified.

127 Adding Database Records
APPEND INSERT

128 Command - APPEND appends a blank record at the end of the database
Syntax: APPEND [BLANK]

129 Command - INSERT inserts a blank record before/after the current record Syntax: INSERT [BEFORE] [BLANK]

130 Deleting Database Records
DELETE RECALL PACK ZAP

131 Command - DELETE marks a record as deleted Syntax:
DELETE [<scope>] [FOR <expL> | WHILE <expL>]

132 Command - RECALL unmarks a deleted record Syntax:
RECALL [<scope>] [FOR <expL> | WHILE <expL>]

133 Command -PACK permanently removes the marked deleted record from the current database. Syntax: PACK

134 Command - ZAP permanently removes all the records from the current database. Syntax: ZAP

135 Example DELETE FOR YEAR(dob) = 1982 LIST RECALL ALL
DELETE FOR DAY(dob) = 6 PACK ZAP

136 Editing Database Records
BLANK BROWSE EDIT REPLACE

137 Command - BLANK clears data in the current record Syntax:
BLANK [FIELDS <field1>[, <field2>...]] [<scope>] [FOR <expL> | WHILE <expL>]

138 Example Clear the data in the name and dob fields in record 9.
BLANK FIELDS name, dob RECORD 9

139 Command - BROWSE opens a window in table (column) form Syntax:
BROWSE [FIELDS <field1>[, <field2>...]] [<scope>] [FOR <expL> | WHILE <expL]

140 Example Open the browse window to show the name, date of birth and average mark of male student. BROWSE FIELDS name, dob, ave_mark FOR sex = “M”

141 Command - EDIT opens a window in row form Syntax:
EDIT [FIELDS <field1>[, <field2>...]] [<scope>] [FOR <expL> | WHILE <expL]

142 Example Open an edit window to show the name and student identity for those who were born in 1983. EDIT FIELDS name, stud_id FOR YEAR(dob) = 1983

143 Command - REPLACE replaces data with the given values Syntax:
REPLACE <field1> WITH <exp1> [, <field2> WITH <exp2>…] [<scope>] [FOR <expL> | WHILE <expL>]

144 Example Replace the average mark with 71.52 in record 7.
REPLACE ave_mark WITH RECORD 7

145 Example For those who have not paid the school fee, have settled now. Update these records. REPLACE paid WITH .T. FOR paid = .F.

146 Reference Visual FoxPro & SQL, Ch. 5 Practical Exercise p.153

147 Questions In the name field, the surname “Yeung” is mistyped as “Yueng”. Correct it by using appropriate functions and command in one statement. Add an extra field “AGE” to StudRec. Then update the field “AGE” by using appropriate functions and command in one statement.

148 Questions REPLACE name WITH
LEFT(name, AT(“ ”, name)) + “Yeung” FOR “Yueng” $ name REPLACE age WITH INT((DATE() - dob)/365.25) ALL

149 Environment Variables
setups the FoxPro environment

150 Commands SET DEFAULT TO [<path>] SET PATH TO [<path>]
setups the working drive and folder. SET PATH TO [<path>] setups the path for searching files

151 Commands SET TALK ON | OFF ON shows the message on status bar. OFF
enables/disables results displayed on status bar. ON shows the message on status bar. OFF hides the messages.

152 Commands SET DECIMALS TO [<expN>]
specifies the number of decimal places. The default is 2. if the <expN> is omitted, the no. of decimal places is set back to default, i.e., 2.

153 Commands SET FIXED ON | OFF ON always shows the decimal places. OFF
specifies whether or not the number of decimal places used in the display of numeric data is fixed. ON always shows the decimal places. OFF shows the decimal places only if the number consists of decimal places.

154 Example SET FIXED ON ?5*5 = 25.00 SET FIXED OFF ?5*5 = 25

155 Commands SET EXACT ON | OFF
specifies the rules used when comparing two strings.

156 Example x = “Vincent” y = “Vincent Chung” SET EXACT OFF
? y = x (returns .T.) SET EXACT ON ? y = x (returns .F.)

157 Commands SET FIELDS TO [<field1>[, <field2>…]]
specifies which field(s) can be accessed. Note that this should be used with SET FIELDS ON | OFF.

158 Commands SET FIELDS ON | OFF ON shows the specified fields. OFF
specifies whether all fields or specific field(s) can be accessed. ON shows the specified fields. OFF shows all the fields.

159 Example SET FIELDS TO name, dob, ave_mark SET FIELDS ON LIST
SET FIELDS OFF

160 Commands SET FILTER TO [<expL>]
specifies a condition that a record must meet to be accessible. if <expL> is omitted, the filter is clear.

161 Example SET FILTER TO sex = “F” LIST SET FILTER TO

162 Commands SET DELETED ON | OFF ON hides the marked deleted records. OFF
specifies whether or not to show the marked deleted record(s). ON hides the marked deleted records. OFF shows the marked deleted records

163 Commands SET DATE TO [FORMAT]
specifies the format of the date. The default FORMAT is MDY. FORMAT MDY DMY YM

164 Reference Visual FoxPro & SQL, Ch. 1, 2, 4 Practical Exercise p.124

165 Searching Database With Criteria
LOCATE CONTINUE

166 Command - LOCATE finds a record with the specified criteria. Syntax:
LOCATE FOR <expL> When the record is found, the record number is shown on the status bar.

167 Command - CONTINUE continues to locate the rest of the records with the specified criteria Syntax: CONTINUE

168 Example Find the database record whose average mark is greater than or equal to 70. LOCATE FOR ave_mark >= 70 CONTINUE

169 Example Find the database record whose year of birth is 1981.
LOCATE FOR YEAR(dob) = 1981 CONTINUE

170 Other Functions FOUND

171 Function - FOUND() returns TRUE if a search is successful, FALSE otherwise. Syntax: FOUND()

172 Example LOCATE FOR "Yeung" $ name ?FOUND() CONTINUE

173 Reference Visual FoxPro & SQL, Ch. 6 - p.157 - 160
Practical Exercise p.195 Ex. 2, 3, 5

174 Database Sorting/Indexing (排序)
SET INDEX SET ORDER REINDEX

175 Command - SORT sorts on particular field(s) and the sorted records are stored in a new database file Syntax: SORT ON <field1> [/A|/D] [/C] [, <field2> [/A|/D] [/C] ...] [<scope>] [FOR <expL> | WHILE <expL>] TO <file>

176 Command - SORT /A - ascending order /D - descending order
/C - ignores case

177 Note Wrong SORT can only sort field, expression is not allowed.
Example SORT ON name, sex TO NameSex SORT ON LEFT(name, 5) TO bbb Wrong

178 Example Sorts the records in descending order of NAME to a new database “dNameStud”. USE StudRec SORT ON name/D TO dNameStud USE dNameStud LIST

179 Example Sorts the records in alphabetical order of SEX, for the same sex, sorts the records in descending order according to STUD_ID. USE StudRec SORT ON sex, stud_id/D TO SexIdStud USE SexIdStud LIST

180 Command - INDEX sorts on particular field in ascending order, an index file with extension “IDX” will be created Syntax: INDEX ON <field1> [+ <field2>...] TO <idx_file>

181 INDEX Example Index according to NAME Database File INDEX File
Rec StudID Name Rec Name An INDEX file is created 1 “F00123” “Peter” 3 “David” 2 “F00007” “John” 2 “John” 3 “F00001” “David” 1 “Peter” 4 “F00014” “Susan” 4 “Susan”

182 Note index file stores the record addresses information, cannot be viewed “+” can only be used if the data type of the fields to be joined are identical to sort numeric expression in descending order, use “-1*<expN>” INDEX can sort on expression

183 Example By using INDEX command, sorts the records in ascending order of SURNAME, for the same surname, sorts the records according to STUD_ID. USE studrec INDEX ON TRIM(SUBSTR(name, AT(“ ”, name) + 1)) + stud_id TO xSurId LIST

184 INDEX Example xSurId.IDX Rec
TRIM(SUBSTR(Name, AT(“ ”, Name) + 1)) + Stud_id 9 “Chans990210” 2 “Chengs990124” 8 “Cheungs990333” 4 “Chows990007”

185 Example By using INDEX command, sorts the records in descending order of AVE_MARK. INDEX ON -1 * ave_mark TO xDAveMk LIST

186 INDEX Example xDAveMk.IDX Rec -1 * Ave_mark 2 -70.24 6 -65.89 3 -62.50
10 -62.25

187 Comparison SORT INDEX Output: database file Output: index file
Order: asc. / desc. Order: asc. field only, no expression e.g., SORT ON name TO dName allows expression e.g., INDEX ON LEFT(name, 3) TO xName

188 Command - SET INDEX opens one or more index files for use with the current database Syntax: SET INDEX TO [<idxfile1>[, <idxfile2>...]]

189 Command - SET ORDER assigns a controlling index file for the current database Syntax: SET ORDER TO [<expN> | <idx_file>]

190 Command - REINDEX updates the opened index files Syntax: REINDEX

191 Example USE StudRec INDEX ON name TO xName INDEX ON dob TO xDob
INDEX ON stud_id TO xStudid CLOSE ALL

192 Example USE StudRec ** open the index file xName ** SET INDEX TO xName
LIST ** add a new record ** APPEND LIST ** open the index file xDob ** SET INDEX TO xDob LIST

193 Example ** update the index file xDob ** REINDEX LIST
** open the index file xStudid ** SET INDEX TO xStudid LIST ** update the index file xStudid ** REINDEX LIST CLOSE ALL

194 Example USE StudRec ** open the index files xName, xDob and xStudid **
SET INDEX TO xName, xDob, xStudid ** add a new record ** APPEND

195 Example LIST ** using the index file xDob ** SET ORDER TO xDob LIST
** using the index file xStudid ** SET ORDER TO xStudid LIST

196 Note - INDEX Order the records in ascending order of F1, then F2.
TESTING.DBF Record F1(N) F2(N) Record F1 F2 1 3 10 2 1 10 2 1 10 3 1 30 3 1 30 1 3 10

197 Note - INDEX INDEX ON F1 + F2 TO temp TESTING.DBF TEMP.IDX Record F1
3 10 2 11 2 1 10 1 13 3 1 30 3 31

198 Note - INDEX INDEX ON F1*1000 + F2 TO temp TESTING.DBF TEMP.IDX Record
3 10 2 1010 2 1 10 3 1030 3 1 30 1 3010

199 Reference Visual FoxPro & SQL, Ch. 6 - p.161 - 175
Practical Exercise p.196 Ex. 8, 9

200 Searching Record in an Indexed Database
FIND SEEK

201 INDEX Example Index according to NAME Database File INDEX File
Rec StudID Name Rec Name An INDEX file is created 1 “F00123” “Peter” 3 “David” 2 “F00007” “John” 2 “John” 3 “F00001” “David” 1 “Peter” 4 “F00014” “Susan” 4 “Susan”

202 Command - FIND searches for the index key that matches the character expression Syntax: FIND <expC> If the search is successful, the record pointer will point to that record, EOF otherwise.

203 Command - SEEK searches for the index key that matches the expression
Syntax: SEEK <expression> If the search is successful, the record pointer will point to that record, EOF otherwise.

204 Example USE studrec ** open the index files xName, xDob and xStudid **
SET INDEX TO xName, xDob, xStudid FIND Victor ** using the index file xStudid ** SET ORDER TO xStudid FIND s990210

205 Example ** using the index file xDob ** SET ORDER TO xDob
SEEK {01/06/83} ** using the index file xStudid ** SET ORDER TO xStudid SEEK “s990333”

206 Comparison LOCATE FIND SEEK search database search index file
all data type. char. only all data type except memo allows condition no condition no condition search next rec. CONTINUE search next rec. SKIP search next rec. SKIP

207 Reference Visual FoxPro & SQL, Ch. 6 - p.179 - 185
Practical Exercise p.196 Ex. 12

208 Database Functions

209 Function - BOF() determines whether the record pointer points at the beginning of the file Syntax: BOF() BOF Record 1 . Record n EOF

210 Function - EOF() determines whether the record pointer points at the end of the file Syntax: EOF() BOF Record 1 . Record n EOF

211 Function - DELETED() determines whether a record is marked deleted or not. Syntax: DELETED() Example LIST FOR DELETED() = .T.

212 Function - RECNO() returns the current record number in the current database Syntax: RECNO() Example ?RECNO()

213 Function - RECCOUNT() returns the total number of records in the current database Syntax: RECCOUNT() Example ?RECCOUNT()

214 Command - APPEND FROM Adds records to the end of the current database from another database Syntax: APPEND FROM <database_file> [FIELDS <field1> [,<field2>...]] [FOR <expL>]

215 Command - APPEND FROM A.DBF B.DBF StudID Name “F00123” “Peter”
“John” “F00001” “David” “F00014” “Susan” Rec 1 2 3 4 StudID Name “F00246” “Peter” “F00017” “John” “F00206” “David” Rec 1 2 3

216 Command - APPEND FROM ** open database A ** A.DBF USE A
** add records from B.DBF to A.DBF ** APPEND FROM B A.DBF StudID Name “F00123” “Peter” “F00007” “John” “F00001” “David” “F00014” “Susan” Rec 1 2 3 4 “F00246” “F00017” “F00206” 5 6 7

217 Command - APPEND FROM A.DBF C.DBF StudID Name “F00123” “Peter”
“John” “F00001” “David” “F00014” “Susan” Rec 1 2 3 4 “F00246” “F00017” “F00206” 5 6 7 Rec StudID 1 “F00369” 2 “F00406”

218 Command - APPEND FROM ** add records from C.DBF to A.DBF A.DBF **
APPEND FROM C A.DBF StudID Name “F00123” “Peter” “F00007” “John” “F00001” “David” “F00014” “Susan” Rec 1 2 3 4 “F00246” “F00017” “F00206” 5 6 7 “F00369” “F00406” 8 9

219 Example - Ch 5 - p.133 USE Metallic APPEND FROM AddMetal LIST

220 Command - COPY TO copies records to a new database file Syntax:
COPY TO <database_file> [FIELDS <field1> [,<field2>...]] [FOR <expL>]

221 Command - COPY TO A.DBF StudID Name “F00123” “Peter” “F00007” “John”
“David” “F00014” “Susan” Rec 1 2 3 4 “F00246” “F00017” “F00206” 5 6 7

222 Command - COPY TO ** copies records to C.DBF ** COPY TO C
FOR VAL(SUBSTR(StudID, 2)) <= 50 C.DBF StudID Name “F00007” “John” “F00001” “David” “F00014” “Susan” Rec 1 2 3 “F00017” 4

223 Data Set Calculations COUNT AVERAGE SUM TOTAL

224 Command - COUNT counts the number of records in the current database. The result is shown on the status bar. Syntax: COUNT [<scope>] [FOR <expL> | WHILE <expL>] [TO <var>]

225 Command - COUNT A.DBF StaffID Name “C01” “Peter” “A10” “John” “M02”
“David” “E09” “Susan” Rec 1 2 3 4 Salary 17000 18000 19000 20000 Sex “M” “F”

226 Example USE ch6ex12 ** find the total number of record ** COUNT
** find the total number of female records in the database ** COUNT FOR sex = “F” ** find the total number of record of “Sales” department and store the result to a variable x ** COUNT FOR department = “Sales” TO x

227 Command - AVERAGE computes the arithmetic mean of the numeric expression / fields. Syntax: AVERAGE [<expression>] [<scope>] [FOR <expL> | WHILE <expL>] [TO <var>]

228 Command - AVERAGE (17000 + 18000 + 19000 + 20000) / 4 A.DBF StaffID
Name “C01” “Peter” “A10” “John” “M02” “David” “E09” “Susan” Rec 1 2 3 4 Salary 17000 18000 19000 20000 Sex “M” “F” ( ) / 4

229 Example USE ch6ex12 ** find the average of all numeric fields **
** find the average salary of female in the database ** AVERAGE salary FOR sex = “F” ** find the average salary of “Sales” department and store the result to a variable x ** AVERAGE salary FOR department = “Sales” TO x

230 Command - SUM finds the sum of the specified numeric field in the current database Syntax: SUM [<expression>] [<scope>] [FOR <expL> | WHILE <expL>] [TO <var>]

231 Command - SUM 17000 + 18000 + 19000 + 20000 A.DBF Rec StaffID Name
Salary Sex 1 “C01” “Peter” 17000 “M” 2 “A10” “John” 18000 “M” 3 “M02” “David” 19000 “M” 4 “E09” “Susan” 20000 “F”

232 Example USE ch6ex12 ** find the total of all numeric fields ** SUM
** find the total salary of “Account” department and store the result to a variable x ** SUM salary FOR department = “Account” TO x

233 Command - TOTAL computes the total of numeric fields by group Syntax:
TOTAL ON <expression> [<scope>] [FOR <expL> | WHILE <expL>] TO <file>

234 Note the database MUST BE indexed on the field to be grouped.
TOTAL computes the sum of NUMERIC fields only.

235 Command - TOTAL Group by sex A.DBF 17000 + 18000 + 19000 20000 Rec
StaffID Name Salary Sex 1 “C01” “Peter” 17000 “M” 19000 2 “A10” “John” 18000 “M” 3 “M02” “David” 19000 “M” 4 “E09” “Susan” 20000 “F” 20000

236 Example (Ch 5 - p.149) USE fruit ** group the result by “fruit” **
INDEX ON fruit TO xFruit TOTAL ON fruit TO temp1 USE temp1 LIST

237 Example USE fruit ** group the result by “class” **
INDEX ON class TO xClass TOTAL ON class TO temp2 USE temp2 LIST

238 Example (Ch 5 - p.149) USE fruit ** group the result by “class” **
INDEX ON class TO xClass TOTAL ON class TO temp2 USE temp2 LIST

239 Multiple Databases

240 Work Area FoxPro opens database in a work area
There are maximum 225 work areas in FoxPro, the default (預設值) is 1 Each work area is associated with an alias (別名) name, the default is the filename of the database, unless it is specified in the USE clause

241 Work Area 1 StudRec

242 Work Area 4 abc 3 studrec 2 sales 1 staff

243 Command - SELECT assigns the working area Syntax:
SELECT <expN> | <expC>

244 Example SELECT 1 USE Client SELECT 2 USE SalesOrder 1 Client
Rec Ptr: 1 2 SalesOrder Rec Ptr: 1 SELECT 2 USE SalesOrder

245 Example SELECT 1 USE Client SELECT 2 USE SalesOrder GO 3 DISPLAY 1
Rec Ptr: 1 2 SELECT 2 USE SalesOrder SalesOrder Rec Ptr: 3 display record 3 GO 3 DISPLAY

246 Example SELECT 1 USE Client SELECT 2 USE SalesOrder GO 3 DISPLAY
Rec Ptr: 1 Display record 1 SELECT 1 USE Client SELECT 2 USE SalesOrder 2 SalesOrder GO 3 DISPLAY Rec Ptr: 3 DISPLAY Client.Order_no

247 Command - SET RELATION Parent Child 2 1 Marks Sreport

248 Note The two databases must have a COMMON FIELD
The common field in the CHILD DATABASE must be UNIQUE The CHILD DATABASE must be INDEXED on that COMMON FIELD

249 Command - SET RELATION establishes a relationship between two or more opened databases Syntax: SET RELATION TO [<exp> INTO <expC>, [<exp> INTO <expC>]...]

250 Example Sreport.dbf Marks.dbf “Stud_id” - common field.
“Stud_id” in Sreport is unique - child database. “Stud_id” in Sreport must be indexed before setting the relationship

251 Example ** assign work area 1 ** SELECT 1
** open the child database “Sreport” ** USE Sreport ** index the common field “stud_id” ** INDEX ON Stud_id TO xStudid

252 Example ** assign work area 2 ** SELECT 2
** open the parent database “Marks” ** USE Marks ** establish the relationship to child “Sreport” through the common field “Stud_id” ** SET RELATION TO Stud_id INTO Sreport

253 Example ** produce a list to show the student name, subject code and mark ** LIST Sreport.Name, Sub_code, Mark

254 Example Subject.dbf Marks.dbf “Sub_code” - common field.
“Sub_code” in Subject is unique - child database. “Sub_code” in Subject must be indexed before setting the relationship

255 Example ** assign work area ** SELECT 1
** open the child database “Subject” ** USE Subject ** index the common field “Sub_code” ** INDEX ON Sub_code TO xSubcode

256 Example ** assign work area ** SELECT 2
** open the parent database “Marks” ** USE Marks ** establish the relationship to child “Subject” through the common field “Sub_code” ** SET RELATION TO Sub_code INTO Subject

257 Example ** produce a list to show the student id, subject description and mark ** LIST Stud_id, Subject.Sub_desc, Mark

258 Example Sreport.dbf, Subject.dbf, Marks.dbf Stud_id Sub_code
common field of Sreport, Marks unique in Sreport - child database must be indexed Sub_code common field of Subject, Marks unique in Subject - child database

259 Example SELECT 1 USE Sreport INDEX ON Stud_id TO xStudid SELECT 2
USE Subject INDEX ON Sub_code TO xSubcode

260 Example SELECT 3 USE Marks SET RELATION TO Stud_id INTO Sreport,
Sub_code INTO Subject LIST Sreport.Name, Subject.Sub_desc, Mark

261 Example It was found that Victor Wong (f99001) his Maths mark was incorrectly entered as 8. The correct mark should be 68. Assuming the relations between the databases have already been established. Update the average mark of Victor Wong.

262 VIEW File It is a file that stores all the information about the FoxPro environment. Information includes: the default path settings databases, index file that are currently open in all work areas relations between databases

263 Command - CREATE VIEW creates a view file from a FoxPro environment
Syntax: CREATE VIEW <file>

264 Command - SET VIEW restores the FoxPro environment from a view file.
Syntax: SET VIEW TO <file>

265 Example ** establish the relationship between “Subject” and “Marks” **
SELECT 1 USE Subject INDEX ON Sub_code TO xSubcode SELECT 2 USE Marks SET RELATION TO Sub_code INTO Subject

266 Example ** create a view file to store the information in the FoxPro environment, i.e., the relationship between the databases ** CREATE VIEW Sreport ** close everything ** CLOSE ALL

267 Example ** open the view file to restore the information, i.e., the relationship between the databases ** SET VIEW TO Sreport ** produce a list to show the student id, subject description and mark ** LIST Stud_id, Subject.Sub_desc, Mark

268 One to One Linkage staff_id class c01 6A c02 6B c03 6C c04 6D a01 6E
. . 6K 6L

269 One to Many Linkage staff_id class subject c01 6A CHN c02 6B CHN c03
ENG c04 6D CHN a01 6E CHN . . 6K CHN 6L ACC

270 Many to One Linkage staff_id class subject c01 6A CHN c02 6B CHN c03
ENG c04 6C CHN a01 6D CHN . . 6J COM 6K ACC

271 Command - UPDATE Master File Transaction File 2 1 Common field
Stock.dbf Purchase.dbf

272 Command - UPDATE Master File Transaction File 2 1 itemNo Stock.dbf
Purchase.dbf itemNo Stock itemNo Qty Date 010 5 011 5 4/1/99 011 2 013 7 4/1/99 012 7 010 4 4/1/99 013 1 011 5 4/2/99 . 013 4 4/2/99

273 Command - UPDATE Master File 2 Stock.dbf itemNo Stock 010 9 011 12 012
7 013 12 .

274 Command - UPDATE updates fields in the current database with data from another database open in another work area Syntax: UPDATE ON <common_field> FROM <expC> REPLACE <field1> WITH <exp1> [, <field2> WITH <exp2>...]

275 Note No need to set the relationship
Handle TWO databases only at a time The two databases must have a COMMON KEY FIELD Both databases must be INDEXED on that COMMON FIELD Condition is not allowed, i.e., FOR

276 Example - UPDATE SELECT 1 USE Strgpurchase
INDEX ON Item_no TO xItemno1 SELECT 2 USE Strgstock INDEX ON Item_no TO xItemno2 UPDATE ON Item_no FROM Strgpurchase REPLACE Newqty WITH Newqty + Strgpurchase.Qty

277 Example - SET RELATION SELECT 1 USE Strgstock
INDEX ON Item_no TO xItemno SELECT 2 USE Strgpurchase SET RELATION TO Item_no INTO Strgstock REPLACE Strgstock.Newqty WITH Strgstock.Newqty + Qty ALL

278 Creating A Report/Label
CREATE REPORT CREATE LABEL

279 Command - CREATE REPORT
creates a report file Syntax: CREATE REPORT <file>

280 Example USE Teaching CREATE REPORT TeachRep
A report designer is open, run a quick report by executing the menu commands: Report >> Quick Report

281 Modifying A Report/Label
MODIFY REPORT MODIFY LABEL

282 Command - MODIFY REPORT
modifies a report file Syntax: MODIFY REPORT <file>

283 Example USE Teaching MODIFY REPORT TeachRep

284 Running A Report/Label
REPORT FORM LABEL FORM

285 Command - REPORT FORM produces a report Syntax:
REPORT FORM <file> [<scope>] [FOR <expL> | WHILE <expL>] [PREVIEW | TO PRINTER]

286 Example USE Teaching REPORT FORM TeachRep FOR Dept = “ACC” PREVIEW

287 Command - LABEL FORM produces a label Syntax:
LABEL FORM <file> [<scope>] [FOR <expL> | WHILE <expL>] [PREVIEW | TO PRINTER]

288 Data Grouping organises data into group.
field(s) to be grouped must be indexed.

289 Example Produces a report to show the staff information that is group by department. Staff_id Name Dept c01 V Chan COM c02 A Chow COM c03 M Tam COM a01 L Wong ACC a02 S Lau ACC .

290 Example Department COM Staff_id Name c01 V Chan c02 A Chow c03 M Tam
ACC Staff_id Name a01 L Wong a02 S Lau

291 Example USE Teaching INDEX ON Dept TO xDept MODIFY REPORT TeachRep
When report designer is open, executing the menu commands: Report >> Data Grouping

292 Example enters the field to be grouped, i.e., Teaching.Dept

293 Data Dictionary information about tables (i.e., fields, type)
relations between tables (i.e., parent, child and their common field) optionally stores the description of fields in another table

294 Command - SET VIEW ON opens the Data Session Window to show the information about the tables. Syntax: SET VIEW ON

295 Command - COPY STRUCTURE EXTENDED
creates a file that stores the description of the fields of a table. Syntax: COPY STRUCTURE EXTENDED TO <file>

296 Copying Files COPY FILE COPY STRUCTURE

297 Command - COPY FILE makes a file copy. Syntax:
COPY FILE <file1> TO <file2> Remember extension must be supplied

298 Command - COPY STRUCTURE
copies an existing database structure to a new file (no records are copied) Syntax: COPY STRUCTURE TO <filename> [FIELDS <list>]

299


Download ppt "Introduction to Databases"

Similar presentations


Ads by Google