Presentation is loading. Please wait.

Presentation is loading. Please wait.

Client/Server Databases and the Oracle 10g Relational Database

Similar presentations


Presentation on theme: "Client/Server Databases and the Oracle 10g Relational Database"— Presentation transcript:

1 Client/Server Databases and the Oracle 10g Relational Database
Chapter 1: Client/Server Databases and the Oracle 10g Relational Database Guide to Oracle 10g

2 Objectives Develop an understanding of the purpose of database systems
Describe the purpose and contents of an entity-relationship model Explain the steps in the normalization process Describe the differences between personal and client/server databases Guide to Oracle 10g

3 Objectives (continued)
Understand the Northwoods University student registration database and the Clearwater Traders sales order database Guide to Oracle 10g

4 Introduction If an organization needs to store and maintain a large amount of data that must be viewed and updated by many users at the same time, it often uses a client/server database such as Oracle 10g. Guide to Oracle 10g

5 Database Systems Data files consist of: Fields Records
Describe characteristics Also called columns Records Group of related fields Guide to Oracle 10g

6 Database Systems (continued)
Problems with storing data in files: Proliferation of data management programs Presence of redundant data Inconsistent data Database Stores all organizational data in central location Eliminates redundant data to reduce possibility of inconsistent data Guide to Oracle 10g

7 Database Systems (continued)
Database management system (DBMS) Application that performs all routine data-handling operations Provides central set of common functions for managing database Inserting Updating Retrieving Deleting data values Guide to Oracle 10g

8 Database Approach to Data Processing
Guide to Oracle 10g

9 Database Systems (continued)
Database administrator Person responsible for installing, administering, and maintaining the database Often called DBA Guide to Oracle 10g

10 Overview of Relational Databases
Table Matrix with columns and rows Columns Represent different data fields Characteristics or attributes about entity Rows Contain individual records Attributes about a specific instance of entity Guide to Oracle 10g

11 Overview of Relational Databases (continued)
Guide to Oracle 10g

12 Overview of Relational Databases (continued)
Entity Object about which you want to store data Different tables store data about each different entity Relationships Links that show how different records are related Guide to Oracle 10g

13 Overview of Relational Databases (continued)
Key fields Establish relationships among records in different tables Main types of key fields Primary Candidate Surrogate Foreign Composite Guide to Oracle 10g

14 Primary Keys Column in relational database table whose value must be unique for each row Serves to identify individual occurrence of entity Every row must have a primary key Cannot be NULL NULL Value is absent or unknown No entry is made for that data element Guide to Oracle 10g

15 Candidate Keys Any column that could be used as the primary key
Should be a column that is unique for each record and does not change Guide to Oracle 10g

16 Surrogate Keys Column created to be record’s primary key identifier
Has no real relationship to row to which it is assigned other than to identify it uniquely Surrogate key values automatically generated using a sequence Guide to Oracle 10g

17 Foreign Keys Column in table that is a primary key in another table
Creates relationship between two tables Value must exist in table where it is the primary key Guide to Oracle 10g

18 Composite Keys Unique key that is created by combining two or more columns Usually comprises fields that are primary keys in other tables Composite Key ORDER_ID PRODUCT_ID ORDER_QUANTITY 100 1 2 200 Guide to Oracle 10g

19 Database Design Main tasks involved with design of database:
Developing entity-relationship (ER) model Normalizing database tables Guide to Oracle 10g

20 Entity-Relationship Model
Designed to help you identify which entities need to be included in database Composed of Squares representing entities Lines representing relationships Types of relationships: One to one (1:1) One to many (1:M) Many to many (N:M) Guide to Oracle 10g

21 Entity-Relationship Model (continued)
One to one (1:1) Each occurrence of a specific entity is found only once in each set of data Rare in relational databases One to many (1:M) Instance can only appear once in one entity, but one or more times in the other entity Guide to Oracle 10g

22 Entity-Relationship Model (continued)
Many to many (N:M) Instance can occur multiple times in each entity Cannot be represented in physical database Broken down into series of two or more 1:M relationships through use of linking table in process of normalization Guide to Oracle 10g

23 Normalization Step-by-step process used to determine which data elements should be stored in which tables Purpose Eliminate data redundancy Several levels of normalization Forms Guide to Oracle 10g

24 Normalization (continued)
Unnormalized data Does not have a primary key identified Contains repeating groups First normal form (1NF) Repeating groups removed Primary key field identified Guide to Oracle 10g

25 Example of Unnormalized Data
Guide to Oracle 10g

26 Normalization (continued)
Second normal form (2NF) In 1NF No partial dependencies Partial dependency Fields within the table are dependent only on part of the primary key Guide to Oracle 10g

27 Normalization (continued)
Basic procedure for identifying partial dependency: Look at each field that is not part of the composite primary key Make certain you are required to have both parts of the composite field to determine the value of the data element Guide to Oracle 10g

28 Normalization (continued)
Third normal form (3NF) In 2NF No transitive dependencies Transitive dependency Field is dependent on another field within the table that is not the primary key field Guide to Oracle 10g

29 Database Systems Consists of Server DBMS Database applications
Manages physical storage and data retrieval Database applications Provide interface that allows users to interact with database Server Computer that shares resources with other computers Guide to Oracle 10g

30 Database Systems (continued)
Server process Program that listens for requests for resources from clients Responds to requests Client Program that requests and uses server resources Guide to Oracle 10g

31 Personal Database Management Systems
DBMS and database applications run on same workstation Appear to user as a single integrated application Used primarily for creating single-user database applications Can also be used for some multiuser applications Should be used only for applications that are not mission critical Guide to Oracle 10g

32 Personal Database Management Systems (continued)
Microsoft Access Stores all data for database in a single file with an .mdb extension Database administrator stores .mdb file on a central file server Guide to Oracle 10g

33 Using a Personal Database for a Multiuser Application
Guide to Oracle 10g

34 Personal Database Management Systems (continued)
Transaction processing Grouping related database changes into units of work that must either all succeed or all fail DBMS can use the transaction log to reverse—or roll back—the changes Guide to Oracle 10g

35 Client/Server Database Management Systems
DBMS server process runs on one workstation Database applications run on separate client workstations across network Server sends only requested data back to client rather than entire database Guide to Oracle 10g

36 Client/Server Database Architecture
Guide to Oracle 10g

37 Client/Server Database Management Systems (continued)
Generate less network traffic than personal databases Extra features to minimize chance of failure Powerful recovery mechanisms that often operate automatically Maintain file-based transaction log on database server Guide to Oracle 10g

38 Client/Server Database Management Systems (continued)
Preferred for Database applications that retrieve and manipulate small amounts of data from databases containing large numbers of records Mission-critical applications Web-based database applications that require increased security and fault tolerance Guide to Oracle 10g

39 The Oracle 10g Client/Server Database
Latest release of Oracle Corporation’s relational database Client/server database Server side DBMS server process Oracle Net Utility that enables network communication between client and server Guide to Oracle 10g

40 Client/Server Architecture for Oracle 10g DBMS
Guide to Oracle 10g

41 The Oracle 10g Client/Server Database (continued)
Oracle Application Server Used to create World Wide Web pages that allow users to access Oracle databases Oracle client products: SQL*Plus Oracle 10g Developer Suite Enterprise Manager Guide to Oracle 10g

42 The Database Cases Fictional organizations: Design principles:
Clearwater Traders Northwoods University Design principles: Convert all tables to third normal form Include primary key as foreign key in table on “many” side of relationship Specify data type for each column Guide to Oracle 10g

43 The Clearwater Traders Sales Order Database
Clothing and sporting goods through mail-order catalogs Wants to begin accepting orders using Web site Required data consists of information for: Customers Orders Items Shipments Guide to Oracle 10g

44 The Clearwater Traders Sales Order Database (continued)
Tables: CUSTOMER ORDER_SOURCE ORDERS CATEGORY ITEM Guide to Oracle 10g

45 The Clearwater Traders Sales Order Database (continued)
Tables (continued): : ORDER_LINE SHIPMENT INVENTORY SHIPMENT_LINE COLOR Guide to Oracle 10g

46 Visual Representation of the Clearwater Traders Database
Guide to Oracle 10g

47 The Northwoods University Student Registration Database
Student registration system Data items consist of information about: Students Courses Instructors Student Enrollment Guide to Oracle 10g

48 The Northwoods University Student Registration Database (continued)
Tables: LOCATION FACULTY STUDENT TERM COURSE COURSE_SECTION ENROLLMENT Guide to Oracle 10g

49 Visual Representation of the Northwoods University Database
Guide to Oracle 10g

50 Summary Relational databases Primary key Foreign key
Store data in tabular format Create relationships that link related data using key columns Primary key Column that uniquely identifies specific record Foreign key Creates relationship between two tables Guide to Oracle 10g

51 Summary (continued) Entity-relationship (ER) model
Used to describe types of relationships between entities Normalization process Used to determine which fields belong in which tables Database system consists of DBMS Database applications Guide to Oracle 10g

52 Summary (continued) Client/server databases divide database into
Server process that runs on network server User application processes that run on individual client workstations Oracle 10g is a client/server database Guide to Oracle 10g

53 Creating and Modifying Database Tables
Guide to Oracle 10g Chapter 2: Creating and Modifying Database Tables Guide to Oracle 10g

54 Database Objects An Oracle database consists of multiple user accounts
Each user account owns database objects Tables Views Stored programs Etc. Guide to Oracle 10g

55 Database Queries Query: command to perform operation on database object Create Modify View Delete Structured Query Language (SQL) Standard query language for relational databases Guide to Oracle 10g

56 SQL Command Types Data Definition Language (DDL)
Used to create and modify the structure of database objects Data Manipulation Language (DML) Used to insert, update, delete, and view database data Guide to Oracle 10g

57 DDL Commands Used to create and modify the structure of database objects CREATE ALTER DROP DDL commands execute as soon as they are issued, and do not need to be explicitly saved Guide to Oracle 10g

58 DML Commands Used to insert, view, and modify database data
UPDATE DELETE SELECT DML commands need to be explicitly saved or rolled back COMMIT ROLLBACK Guide to Oracle 10g

59 User Accounts Each Oracle database user has a user schema
Area in the database where the user’s database objects are stored Identified by a unique username and protected by a password Each user schema is granted specific privileges Guide to Oracle 10g

60 Types of Database Privileges
System Privileges Control the operations that the user can perform within the database Connecting to the database (Create Session), creating new tables, shutting down the database, etc. Object Privileges Granted on individual database objects Controls operations that a user can perform on a specific object (insert data, delete data, etc.) When you create an object in your user schema, you can then grant object privileges on that object to other database users Guide to Oracle 10g

61 Break Time: SQL Plus Oracle SQL command line utility for issuing SQL commands Starting SQL Plus LOGON to YOUR Oracle Account Guide to Oracle 10g

62 How to Access Your Oracle Account
1. Click the START button, point to Programs 2. Select Oracle –Oracle10g, then 3. Click Application Development, then 4. Select SQL PLUS User Name: Password: Host string: Guide to Oracle 10g

63 Creating New User Accounts
Done by DBA Syntax: CREATE username IDENTIFIED BY password; Guide to Oracle 10g

64 Oracle Naming Standard
Oracle database objects must adhere to the Oracle Naming Standard 1 to 30 characters long Must begin with a character Can contain characters, numbers, and the symbols $, _, and # Guide to Oracle 10g

65 Defining Database Tables
To create a table, you must specify: Table name Field names Field data types Field sizes Constraints Guide to Oracle 10g

66 Table and Field Names Must follow the Oracle Naming Standard
Each table in a user schema must have a unique name within that user schema Each field in a table must have a unique name within that table Guide to Oracle 10g

67 CREATE TABLE tablename
Creating a Table CREATE TABLE tablename (fieldname1 data_type, (fieldname2 data_type, …) Guide to Oracle 10g

68 Oracle Data Types Data type: specifies type of data stored in a field
Date, character, number. LONG, RAW, LONG RAW, BLOB Uses Error checking Efficient use of storage space Guide to Oracle 10g

69 Oracle Character Data Types
VARCHAR2 columnname VARCHAR2(max_size) Variable-length character strings Max_size can be between 1 and 4,000 characters Must specify the size No trailing blank spaces are added If more than max_size data is inserted, an error occurs. Example declaration: student_name VARCHAR2(30) Guide to Oracle 10g

70 Character Data Types CHAR columnname CHAR(max_size)
Fixed-length character data Max_size can be between 1 and 2000 characters Max_size is optional. Default is 1. Adds trailing blank spaces to pad width If more than max_size data is inserted, an error occurs. Example declaration: student_gender CHAR(2) Guide to Oracle 10g

71 Character Subtypes Examples: VARCHAR2(5) ‘Smith’ or ‘Smi’
Guide to Oracle 10g

72 Question: Which query will possibly generate student information?
s_last CHAR(15); SELECT s_last, s_first, s_address FROM student WHERE s_last = ‘Smith’; s_last VARCHAR2(15); SELECT s_last, s_first, s_address FROM student WHERE s_last = ‘Smith’; What data type should be used if there is any chance that all column spaces will NOT be filled? Answer: VARCHAR2 Guide to Oracle 10g

73 Character Data Types 3. NVARCHAR2 and NCHAR
Analogous to VARCHAR2 and CHAR but use Unicode rather than ASCII Used to hold character data in languages other than English (Japanese). Guide to Oracle 10g

74 Number Data Type NUMBER General declaration format:
stores negative, positive, fixed, and floating point numbers values between and 10126 General declaration format: variable_name NUMBER(precision, scale) Guide to Oracle 10g

75 NUMBER Data Types Number type (integer, fixed point, floating point) specified by precision and scale Precision: total number of digits on either side of the decimal point. It does not include the decimal point itself or any commas or any formatting symbols. Scale: number of digits to right of decimal point Guide to Oracle 10g

76 Integer Numbers Whole number with no digits to right of decimal point
Precision is maximum width Scale is omitted Sample declaration: s_age NUMBER (2) Guide to Oracle 10g

77 Fixed Point Numbers Contain a specific number of decimal places
Precision is maximum width Scale is number of decimal places Sample declaration: item_price NUMBER(5, 2) (decimal point is not included) Guide to Oracle 10g

78 Floating Point Numbers
Contain a variable number of decimal places Precision and scale are omitted Sample declaration: s_GPA NUMBER Guide to Oracle 10g

79 Date Data Type DATE Default date format: DD-MON-YY HH:MI:SS AM
Stores dates from 1/1/4712 BC to 12/31/4712 AD Stores both a date and time component Default date format: DD-MON-YY HH:MI:SS AM example: 05-JUN-03 12:00:00 AM Sample declaration: s_dob DATE Guide to Oracle 10g

80 Specifying Date and Time Values
If no time value is given when a new date is inserted, default value is 12:00:00 AM If no date value is given when a new time is inserted, default date is first day of current month Guide to Oracle 10g

81 TIMESTAMP Data Type The same as Date DT, but it stores also fractional seconds. Field Timestamp(Fr_Se_Precision) E.g: ship_dt Timestamp(2) Fractional Seconds Precision default value is 6 (If omitted). Guide to Oracle 10g

82 Interval Year to Month Data Type
Field Interval Year(Y_Pr) To Month. Y_Pr: Year Precision(Default: 6). E.g: elapsed Interval Year(2) To Month. Possible Values: :add 2 years and 11 months to a known date. -11-4:subtract 11 years and 4 months. Guide to Oracle 10g

83 Interval Day to Second Data Type
Field Interval Day(D_Pr) To Second(Fr_Se_pr). D_Pr: Day Precision(Default : 2). Fr_Se_Pr: Fractional Seconds Precision (Default : 6). Possible value: -04 03:20:32.00 (Days Hours:Minutes:Seconds.Fractions) Guide to Oracle 10g

84 Large Object (LOB) Data Types
Binary Large Object (BLOB) Stores up to 4 GB of binary data Character Large Object (CLOB) Stores up to 4 GB of character data BFILE Stores a reference to a binary file maintained in the operating system NCLOB Character LOB that supports 16-bit character code Guide to Oracle 10g

85 6. Large Object (LOB) Data Types
Ex: f_image BLOB; Guide to Oracle 10g

86 Declaring LOB Data Fields
Item size is not specified Examples: item_image BLOB item_image BFILE Guide to Oracle 10g

87 Creating a Database Table
Syntax: CREATE TABLE table_name ( fieldname1 datatype, fieldname2 datatype, …); Example: CREATE TABLE my_students ( s_id NUMBER(6), s_name VARCHAR2(30), s_dob DATE, s_class CHAR(2)); Guide to Oracle 10g

88 Constraints Rules that restrict the values that can be inserted into a field Types of constraints Integrity: define primary and foreign keys Value: specify values or ranges of values that can be inserted Guide to Oracle 10g

89 Constraint Levels Table constraint Column constraint
Restricts the value of a field with respect to all other table records Example: primary key value must be unique for each record Column constraint Restricts values in a specific column Example: values in an S_GENDER field must be ‘M’ or ‘F’ Guide to Oracle 10g

90 Constraint Names Internal name used by DBMS to identify the constraint
Each constraint name in a user schema must be unique If you do not name a constraint, the system will automatically generate an unintuitive name starts with SYS_Cn. n is a numeric value. Guide to Oracle 10g

91 Constraint Names Constraint naming convention: Constraint ID values:
tablename_fieldname_constraintID Constraint ID values: Primary key: pk Foreign key: fk Check condition: cc Not NULL: nn Unique: uk Example constraint name: my_students_s_id_pk Guide to Oracle 10g

92 Constraint Names 10g too Guide to Oracle 10g

93 Primary Key Constraints
Table-level Defining a primary key: CONSTRAINT constraint_name PRIMARY KEY Example: s_id NUMBER(6) CONSTRAINT student_s_id_pk PRIMARY KEY Guide to Oracle 10g

94 Primary Key Constraints
Can be defined when field is declared Guide to Oracle 10g

95 Primary Key Constraints
Can also be defined after all table field definitions are completed Guide to Oracle 10g

96 Composite Primary Keys
Syntax: CONSTRAINT constraint_name PRIMARY KEY (field1, field2) Must be defined after fields that compose key are defined Guide to Oracle 10g

97 Foreign Key Constraints
Table-level Can only be defined after field is defined as a primary key in another table Syntax: CONSTRAINT constraint_name REFERENCES primary_key_table_name (field_name) Guide to Oracle 10g

98 Foreign Key Constraints
Can be defined when field is declared NOTE: faculty TABLE MUST EXIST BEFORE my_students. Guide to Oracle 10g

99 Foreign Key Constraints
Can also be defined after all table field definitions are completed Guide to Oracle 10g

100 Value Constraints Column-level
Restricts data values that can be inserted in a field In general, avoid value constraints because they make the database very inflexible Guide to Oracle 10g

101 Types of Value Constraints
Check condition: restricts to specific values Example: s_gender (M or F) CONSTRAINT my_students_s_gender_cc CHECK (s_gender = ‘M’) OR (s_gender = ‘F’) Not NULL: specifies that a field cannot be NULL Example: CONSTRAINT my_students_s_dob_nn NOT NULL Guide to Oracle 10g

102 Types of Value Constraints
Default: specifies a default value that is inserted automatically unless the user insert an other value Example: Must be created in the column declaration, NOT a separate command beginning with CONSTRAINT. s_state CHAR(2) DEFAULT ‘WI’ Unique Table constraint Specifies that a non-primary key field must have a unique value CONSTRAINT consultant_c_ _uk UNIQUE (c_ ) (Primary key constrain does not allow NULL, but this does) Guide to Oracle 10g

103 SQL*Plus Oracle SQL command line utility for issuing SQL commands
Starting SQL*Plus Guide to Oracle 10g

104 Using SQL*Plus All commands must be terminated with a semicolon (;)
Use a text editor and copy and paste commands Character data is case sensitive and must be in single quotes ‘M’ ‘Sarah’ Commands are NOT case sensitive. Guide to Oracle 10g

105 Exiting SQL*Plus Type exit at SQL> prompt
or Click Close button on SQL*Plus window Guide to Oracle 10g

106 Oracle Help Resources Ora.hlp file Oracle Technology Network (OTN)
Guide to Oracle 10g

107 Create a Table Guide to Oracle 10g

108 Using Notepad Useful to use Notepad to edit sql commands
Commands can be edited without retyping Commands can be saved Saving multiple sql commands in a file creates a script Guide to Oracle 10g

109 Study … Can you create TABLE student now? Guide to Oracle 10g

110 Table Creation Sequence
When creating tables with foreign key references, create referenced tables first Always create tables without foreign keys before those with foreign keys Guide to Oracle 10g

111 Viewing Table Information
Viewing a table’s structure DESCRIBE table_name; Guide to Oracle 10g

112 Oracle Data Dictionary
Contains tables that describe the database structure Is in the SYSTEM user schema Is automatically updated as users create and modify tables Cannot be updated directly Contains views that allow users to retrieve information about the database structure View: is a db object that the DBMS bases on an actual db table and which enables the DBMS to present the table data in a different format based on user needs. It can serve to hide some table columns in which the user has no interest or doesn’t have privileges to view. Guide to Oracle 10g

113 Data Dictionary Views Views present data in different formats depending on the privileges of the user USER: shows all objects belonging to the current user ALL: shows all objects belonging to the current user, as well as objects current user has privileges to manipulate DBA: allows users with DBA privileges to view objects of all database users Guide to Oracle 10g

114 Querying the Data Dictionary Views
Syntax: SELECT view_columnname1, view_columnname2, … FROM prefix_object; Try: DESCRIBE user_tables; to see the details of that table. Guide to Oracle 10g

115 Viewing Information About Tables
General command: SELECT view_columnname1, view_columnname2, … FROM prefix_object; view_columnname1, view_columnname2,… are the name of the fields you want to retrieve from the view. prefix: either USER, ALL or DBA. object: the type of the DB object you are examining. See next slide for these objects. Ex: select table_name from user_tables; Table_name is a field name in the table user_tables. User_tables is a table saves the names of all the table you (user) create. Guide to Oracle 10g

116 Database Objects with Data Dictionary View
Object Name Object Type OBJECTS All database objects TABLES Database tables INDEXES Table indexes created to improve query performance VIEWS Database views SEQUENCES Sequences created to automatically generate surrogate key values USERS Database users CONSTRAINTS Table constraints CONS_COLUMNS Table columns that have constraints IND_COLUMNS Indexed columns TAB_COLUMNS All table columns Guide to Oracle 10g

117 Viewing Constraints on One Table
Try: DESCRIBE user_constraints; to see the details of that table. Guide to Oracle 10g

118 Modifying Tables Unrestricted actions: some specifications can always be modified. Renaming tables Adding new columns Increasing column sizes Dropping columns Dropping constraints Guide to Oracle 10g

119 Modifying Tables Restricted actions:specifications modified only in certain situations Dropping tables Only allowed if table does not contain any fields that are referenced as foreign keys, or if foreign key constraints are dropped Changing a column’s data specification Only allowed if existing data is compatible with new data specification Decreasing column sizes Only allowed if column does not contain any data Adding constraints Only allowed if existing data meets requirements of new constraint Guide to Oracle 10g

120 Deleting and Renaming Tables
To delete: DROP TABLE [tablename] Use with caution. It is a restricted actions, can not be dropped if it contains a foreign key. Delete the constraint and then drop the table or use cascade. To delete foreign key constraints, add “CASCADE CONSTRAINTS” To rename: RENAME old_tablename TO new_tablename DBMS automatically transfers to the new table integrity constraints, indexes, and privileges that referenced the old table. Views and stored program units that reference the old table name become Invalid. Guide to Oracle 10g

121 Altering Tables Adding a new field: ALTER TABLE tablename
ADD (fieldname field_specification); Guide to Oracle 10g

122 Altering Tables Modifying an existing field:
ALTER TABLE tablename MODIFY (fieldname new_field_specification); Can only change data type to compatible data type (i.e. varchar2 to char) Guide to Oracle 10g

123 Altering Tables Deleting an existing field: ALTER TABLE tablename
DROP COLUMN fieldname; ALTER TABLE faculty ADD (faculty_rank VARCHAR2(4)); Guide to Oracle 10g

124 Renaming a Column ALTER TABLE tablename To rename a field
RENAME COLUMN old_fieldname TO new_fieldname; Ex: ALTER TABLE faculty RENAME COLUMN faculty_rank to f_rank; Guide to Oracle 10g

125 Adding and Deleting Constraints
Add a constraint: ALTER TABLE tablename ADD CONSTRAINT constraint_name constraint_definition; Remove a constraint: DROP CONSTRAINT constraint_name; Examples: ALTER TABLE faculty ADD CONSTRAINT faculty_f_pin_uk UNIQUE (f_pin); DROP CONSTRAINT faculty_f_pin_uk; Guide to Oracle 10g

126 Enabling and Disabling Constraints
When modifying a database it can be useful to disable constraints Constraints are enabled by default To disable a constraint: ALTER TABLE tablename DISABLE CONSTRAINT constraint_name; To enable a constraint: ENABLE CONSTRAINT constraint_name; ALTER TABLE faculty DISABLE CONSTRAINT faculty_loc_id_fk; ENABLE CONSTRAINT faculty_loc_id_fk; DROP TABLE faculty CASCADE CONSTRAINTS; EXIT; Guide to Oracle 10g

127 Deleting Tables Syntax to delete table if no table fields are referenced as foreign keys: DROP TABLE tablename; Syntax to delete table and constraints if table contains fields that are referenced as foreign keys: DROP TABLE tablename CASCADE CONSTRAINTS; Guide to Oracle 10g

128 Summary SQL commands include: To create a table:
Data description language (DDL) commands: create, modify, Deleted database objects Data manipulation language (DML) commands: insert, update, delete, view database data To create a table: specify the table name, the name of each data field, and the data type and size of each data field Data types ensure correct data values Constraints restrict values of database fields SQL*Plus commands are not case sensitive Guide to Oracle 10g

129 Summary (cont.) Errors include line number, position, error code
Use DESCRIBE command to display a table’s fieldnames and data types Tables can be modified or deleted but some changes are restricted Guide to Oracle 10g

130 End Of Chapter 2 Guide to Oracle 10g

131 Enhanced Guide to Oracle 10g
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data Teaching Tip: If you are using this slideshow in a computer classroom, students can enter commands to the MY_FACULTY and MY_STUDENTS tables as you introduce them. Before using this slideshow, create the tables using the following commands: CREATE TABLE my_faculty (f_id NUMBER(6), f_name VARCHAR2(30)); CREATE TABLE my_students (s_name VARCHAR2 (30), s_dob DATE, s_class CHAR(2), s_age NUMBER(2)); Then have students enter commands as they are introduced. Guide to Oracle 10g

132 Queries and action queries
Queries are the DML commands that allow users to retrieve database data, because the retrieved data are answers to questions. Action queries are the DML commands that insert, update, or delete database data, because the commands perform an action that change the data value. Guide to Oracle 10g

133 SQL Scripts Script: text file that contains a sequence of SQL commands. Usually have .sql extension Running a script: SQL> START path_to_script_file; OR path_to_script_file; Path cannot contain any blank spaces Guide to Oracle 10g

134 Inserting a Value Into Every Field in a Record
Syntax: INSERT INTO tablename VALUES (column1_value, column2_value, …); You must insert a value or a NULL placeholder for every field. Fields must be entered in the order they appear in the table when you issue the DESCRIBE command. Guide to Oracle 10g

135 Inserting a Value Into Every Field in a Record
Example: Guide to Oracle 10g

136 Inserting Selected Table Fields
Command to insert values for selected record fields: INSERT INTO tablename (column1_name, column2_name, …) VALUES (column1_value, column2_value, …); Guide to Oracle 10g

137 Inserting Selected Table Fields
Example: Guide to Oracle 10g

138 Format Models (Masks) All data is stored in the database in a standard binary format Format masks are alphanumeric text strings that specify the format of input and output data Table 3-1: Number format masks Table 3-2: Date format masks Guide to Oracle 10g

139 Inserting Date Values Date values must be converted from characters to dates using the TO_DATE function and a format mask Example: Guide to Oracle 10g

140 Inserting Text Data Must be enclosed in single quotes
Is case-sensitive To insert a string with a single quote, type the single quote twice Example: 'Mike''s Motorcycle Shop' Guide to Oracle 10g

141 Inserting Interval Values
Year To Month Interval: TO_YMINTERVAL(‘years-months’) e.g. TO_YMINTERVAL(‘3-2’) Day To Second Interval: TO_DSINTERVAL(‘days HH:MI:SS.99’) e.g. TO_DSINTERVAL(‘-0 01:15:00’) Guide to Oracle 10g

142 Inserting LOB Column Locators
Oracle stores LOB data in a separate physical location from other types of data in a row. Before inserting data in a LOB column, a locator must be inserted first. A locator is a structure that contains information that identifies the LOB data type and points to the alternate memory location. After that a program or a utility is needed to insert the data into the DB (chapter 10). Ex. To create a locator for a BLOB data: EMPTY_BLOB(); Another example page 96. Guide to Oracle 10g

143 Transactions Transaction
Logical unit of work consisting of one or more SQL DML commands INSERT, UPDATE, DELETE All transaction commands must succeed or none can succeed Transaction results are not visible to other users until they are “committed” to the database (this is not the case with DDL commands) Until a transaction is committed, it can easily be “rolled back” (undone) Guide to Oracle 10g

144 Transactions A transaction starts when you type one or more DML commands in SQL*Plus A transaction ends when you issue either the COMMIT or ROLLBACK command SQL>COMMIT; SQL>ROLLBACK; Guide to Oracle 10g

145 Committing and Rolling Back Data
Makes transaction command changes permanent in the database and visible to other users ROLLBACK Rolls back transaction command changes and restores database to its state before the transaction Guide to Oracle 10g

146 Savepoints Used to mark individual sections of a transaction
You can roll back a transaction to a savepoint Guide to Oracle 10g

147 Search Conditions Format: Operators
WHERE fieldname operator expression Operators Equal (=) Greater than, Less than (>, <) Greater than or Equal to (>=) Less than or Equal to (<=) Not equal (< >, !=, ^=) LIKE BETWEEN IN NOT IN Guide to Oracle 10g

148 Search Condition Examples
WHERE s_name = ‘Sarah’ WHERE s_age > 18 WHERE s_class <> ‘SR’ Text in single quotes is case sensitive Guide to Oracle 10g

149 Updating Records Syntax:
UPDATE tablename SET column1 = new_value, column2 = new_value, … WHERE search_condition; Each update statement can update row(s) in one table only Can update multiple records if they all match the search condition Guide to Oracle 10g

150 Deleting Records Syntax:
DELETE FROM tablename WHERE search_condition; Deletes multiple records if search condition specifies multiple records If search condition is omitted, all table records are deleted You can’t delete a record if it contains a primary key value that is referenced as a foreign key Guide to Oracle 10g

151 Truncating Tables Removes ALL table data WITHOUT saving any rollback information (DELETE needs to save a copy of all the deleted records for a rollback possibility) Advantage: fast way to delete table data Disadvantage: can’t be undone (rollback) Syntax: TRUNCATE TABLE tablename; Guide to Oracle 10g

152 Truncating Tables You can not truncate a table that has an enabled foreign key constrain. So you need to disable the constraint first: Syntax: TRUNCATE TABLE tablename DISABLE CONSTRAINT constraint_name; Guide to Oracle 10g

153 Sequences Sequential list of numbers that is automatically generated by the database Used to generate unique values for surrogate keys Guide to Oracle 10g

154 Creating Sequences Syntax: CREATE SEQUENCE sequence_name
[optional parameters]; Example: CREATE SEQUENCE f_id_sequence START WITH 200; Guide to Oracle 10g

155 Viewing Sequence Information
Query the SEQUENCE Data Dictionary View: (user_sequences) see table 2.3 p.69 Guide to Oracle 10g

156 Pseudocolumns To use sequences, psedocolumns should be understood first. Psedocolumns acts like a column in a database table, but it is actually a command that returns a specific value. Used to retrieve: Current system date Name of the current database user Next or Current values of a sequence Guide to Oracle 10g

157 Pseudocolumn Examples
Name Output CURRVAL Most recently retrieved sequence value NEXTVAL Next value in a sequence SYSDATE Current system date from database server USER Username of current user Guide to Oracle 10g

158 Using Pseudocolumns Retrieving the current system date:
SELECT SYSDATE FROM DUAL; Retrieving the name of the current user: SELECT USER DUAL is a system table that is used with pseudocolumns. It contains one column. Its value can not be deleted or modified. (P.110) Guide to Oracle 10g

159 Using Pseudocolumns With Sequences
Accessing the next value in a sequence: sequence_name.NEXTVAL (Can you know the retrieved value before using it?) see next slide. Inserting a new record using a sequence: INSERT INTO my_faculty VALUES (f_id_sequence.nextval, ‘Professor Jones’); Guide to Oracle 10g

160 Seeing value of sequences
The following command shows the NEXT value of the sequence: SELECT sequence_name.NEXTVAL FROM DUAL; The following command shows the current value of the sequence: SELECT sequence_name.CURRVAL FROM DUAL; See example page 111. Accessing CURRVAL without NEXTVAL in advance cause an error. See example page 112. Guide to Oracle 10g

161 Deleting Sequencing The following DDL command drops sequences from a DB: DROP SEQUENCE sequence_name; No need for commit with DDL commands. Guide to Oracle 10g

162 Object Privileges Permissions that you can grant to other users to allow them to access or modify your database objects Object Type Privilege Description Table, Sequence ALTER Allows user to change object’s structure using the ALTER command DROP Allows user to drop object SELECT Allows user to view object Table INSERT, UPDATE, DELETE Allows user to insert, update, delete table data Any database object ALL Allows user to perform any operation on object Guide to Oracle 10g

163 Syntax Granting object privileges:
GRANT privilege1, privilege2, … ON object_name TO user1, user 2, …; Revoking (cancel) object privileges: REVOKE privilege1, privilege2, … FROM user1, user 2, …; Guide to Oracle 10g

164 Granting and Revoking Object Privileges
Guide to Oracle 10g

165 Retrieving Data From a Single Table
Syntax: SELECT column1, column2, … FROM tablename WHERE search_condition; Guide to Oracle 10g

166 Retrieving Data From a Single Table
To retrieve every column in a table: SELECT * FROM … To retrieve every record in a table, omit the search condition SELECT column1, column2, … FROM tablename; Guide to Oracle 10g

167 Qualifying Table Names
If you retrieve data from a table that is owned by another user, you must qualify the table name by prefacing it with the owner’s name. (we will study it again when joining multiple tables P.159) Guide to Oracle 10g

168 Suppressing Duplicate Records
Sometimes queries retrieve duplicate records To suppress duplicate outputs, use the DISTINCT qualifier: SELECT DISTINCT column1, column2, … FROM ... Guide to Oracle 10g

169 Using Multiple Search Conditions
Use the search condition (where) to retrieve rows matching specific criteria. Combining search conditions AND: both conditions must be true OR: either condition can be true Combining AND and OR in a single operation AND comparisons are evaluated first Always use parentheses to force conditions to be evaluated in the correct order Guide to Oracle 10g

170 Example SQL> SELECT room FROM location WHERE bldg_code = ‘BUS’
AND capacity >= 40; Guide to Oracle 10g

171 Searching for NULL Records
NULL: not defined Use IS NULL search condition SELECT s_name, s_class FROM my_students WHERE s_class IS NULL; Guide to Oracle 10g

172 Searching for NOT NULL Records
Use IS NOT NULL operator SELECT s_name, s_age FROM my_students WHERE s_class IS NOT NULL; Guide to Oracle 10g

173 Using the IN and NOT IN Operators
IN retrieves all values where the search column value matches a set of values SELECT * FROM enrollment WHERE grade IN (‘A’, ‘B’); Either A or B. Guide to Oracle 10g

174 Using the IN and NOT IN Operators
NOT IN retrieves all values where the search column value matches a set of values SELECT * FROM enrollment WHERE grade NOT IN (‘A’, ‘B’); Neither A or B. Guide to Oracle 10g

175 Using the LIKE Operator
Performs inexact searches by matching part of a character string WHERE fieldname LIKE character_string; Guide to Oracle 10g

176 Using the LIKE Operator
Character string must be in single quotes and use wildcard characters (%) represents multiple wildcard characters ‘%2006’ Exact search of a string its right characters same as ‘2006’, it ignores anything on the left (no matter how many characters are there). ‘FALL%’ all rows in which the first 4 characters are FALL. (_) Underscore represents a single wildcard character ‘_R’ retrieve all values its first character can be any value, but the second must be ‘R’. Wildcard characters can be placed at beginning or end of string Guide to Oracle 10g

177 Examples Using the LIKE Operator
SELECT * from term WHERE term_desc LIKE ‘Fall%’; SELECT course_no FROM course WHERE course_no LIKE ‘%1__’; Two underscores Guide to Oracle 10g

178 Sorting Query Output Use the ORDER BY clause
Specify sort key, which is the column used as a basis for ordering the output data SELECT s_name, s_age FROM my_students ORDER BY s_age; Guide to Oracle 10g

179 Sorting Query Data Default sort order Numerical: ascending
Character: A - Z Date: oldest - newest To force the sort order: use ASC or DESC Example SELECT s_name, s_age FROM my_students ORDER BY s_age DESC; You can specify multiple sort keys. Example P. 131. Guide to Oracle 10g

180 Using Calculations in Queries
Calculation using SQL directly is efficient, because the result is returned to the client calculated. Arithmetic operations on retrieved data Addition (+) Subtraction (-) Multiplication (*) Division (/) Calculations are performed on NUMBER, DATE, and INTERVAL data types. Guide to Oracle 10g

181 Example Calculations in Queries
SELECT inv_id, inv_qoh * inv_price FROM inventory; Date calculations involve the current date. To retrieve the current date from the server use: SELECT SYSDATE FROM DUAL; And then use it in equations: SYSDATE – o_date Guide to Oracle 10g

182 Example Calculations in Queries
Remember that time_enrolled is an INTERVAL data type in STUDENT table. SELECT s_id, s_last, SYSDATE – time_enrolled FROM student; Remember to use SELECT SYSDATE FROM DUAL first. Guide to Oracle 10g

183 Single-Row Number Functions
Called so, because they return a single result for each row of data retrieved. ABS - absolute value CEIL – rounds a number up to the next integer FLOOR – rounds a number down to the previous integer MOD – returns the remainder of a number and a divisor POWER - raises a number to an exponent ROUND - rounds a number SQRT – returns the square root of a value TRUNC - truncates a number to the nearest whole number Table 3-7 P. 137. Guide to Oracle 10g

184 Using Single-Row Number Functions
Example: SELECT s_name, TRUNC((SYSDATE - s_dob)/365) FROM my_students; Guide to Oracle 10g

185 Single-Row Character Functions
CONCAT – joins 2 character strings INITCAP – returns a string with the initial letter only uppercase LENGTH – returns the length of a string LPAD, RPAD – returns a string with a specific number of characters added on the left or right side LTRIM, RTRIM – returns a string with all instances of a specific character trimmed from the left or right side REPLACE – replaces all instances of a character with another character UPPER/LOWER – returns a string in all upper/lower case letters Table 3-8 P. 139 Guide to Oracle 10g

186 Using Single-Row Character Functions
Example: SELECT UPPER(s_name) FROM my_students; Guide to Oracle 10g

187 Date Arithmetic To find a date that is a specific number of days before or after a known date, add or subtract the number from the known date Example: SELECT order_date + 30 FROM cust_order; Guide to Oracle 10g

188 Date Arithmetic To find the number of days between two known dates, subtract the later date from the earlier date Example: SELECT SYSDATE – s_dob FROM my_students; Guide to Oracle 10g

189 Single-row Date Functions
ADD_MONTHS returns a date that is a specific number of months after a given date Example: SELECT ADD_MONTHS(SYSDATE, 6) FROM dual; Guide to Oracle 10g

190 Date Functions LAST_DATE Example:
Returns the date that is the last day of the month specified in the current date Example: SELECT LAST_DATE(order_date) FROM cust_order WHERE order_id = 1057; Guide to Oracle 10g

191 Date Functions MONTHS_BETWEEN Example:
Returns the number of months between two input dates Example: SELECT MONTHS_BETWEEN(order_date, SYSDATE) FROM cust_order WHERE order_id = 1057; Guide to Oracle 10g

192 Group Functions Used to perform an operation on a field from a group of retrieved records AVG (average of all retrieved values) COUNT (number of records retrieved) MAX (maximum value retrieved) MIN (minimum value retrieved) SUM (sum of all retrieved values) Guide to Oracle 10g

193 Group Function Examples
SELECT AVG (s_age) FROM my_students; SELECT MAX (s_age) FROM my_students; SELECT MIN (s_age) FROM my_students; SELECT SUM (s_age) FROM my_students; Guide to Oracle 10g

194 Using the GROUP BY Clause
Group the output by the column with duplicate values and apply group functions to the grouped data. Example: SELECT bldg_code, SUM(capacity) FROM location GROUP BY bldg_code; The bldg_code has 3 values(CR,BUS,LIB) see page 31. Each value has several occurrences, BUS=7 times. So the query group the occurrences of each value and AVG the capacity of each. See result page 145. Note that AVG(capacity)without group by gives different results. NOT as desired. THINK! Guide to Oracle 10g

195 Using the HAVING Clause
Is used to filter grouped data. It can be used to place condition on the results of queries that display group function calculation. Example: SELECT bldg_code, SUM(capacity) FROM location HAVING SUM(capacity) >= 100 GROUP BY bldg_code; Here we are interested in the total capacity of more than 99 for each building. Guide to Oracle 10g

196 Creating Alternate Column Headings in SQL*Plus
Formatting output: did you notice the output of the queries? the column name appeared as it is in the DB or the calculation formula. To display a different headings: Syntax: SELECT column1 “heading1”, column2 “heading2”, … Example: SELECT bldg_code “Building”, SUM(capacity) “Building Capacity” FROM location GROUP BY bldg_code; Might contain spaces. Example (Building Capacity) See output page 147. Guide to Oracle 10g

197 Creating a Column Alias
Column alias: is an alternate column name that can be referenced in the ORDER BY and GROUP BY clauses Syntax: SELECT column1 AS alias1 … Example: SELECT (SYSDATE – s_dob) AS age_alias ORDER BY age_alias Can NOT contain space. Guide to Oracle 10g

198 SQL* Plus Environment Options  Environment
Linessize Custom  120 (char/line) Pagesize  Custom  40 (line/page) OK Guide to Oracle 10g

199 Formatting Data Using the TO_CHAR Function
Used to display NUMBER and DATE values using a specific format mask (model table 3-2 page 92) Syntax: TO_CHAR(fieldname, ‘format_mask’); Note the single quote. Example SELECT c_sec_id, sec_num,c_sec_day, TO_CHAR(c_sec_time, ‘HH:M1 AM’) FROM course_section; See output page 152. See example page 152 for currency format. Guide to Oracle 10g

200 Join Queries Retrieve data from multiple tables by joining tables using foreign key references Syntax SELECT col1, col2, … FROM table1, table2 WHERE table1.joincol = table2.joincol AND search_condition(s); Qualify a column by specifying the table that contains the column followed by a period and then the column name. The WHERE clause contains the join condition, which contains the foreign key reference and the primary key in the other table. Search condition is added using AND or OR operators. Guide to Oracle 10g

201 Join Queries Types Join query types: Inner (equality) Outer Self
Inequality Guide to Oracle 10g

202 Inner Joins Occurs when joining two tables based on values in one table being equal to values in another table. Guide to Oracle 10g

203 Inner Joins Syntax: SELECT column1, column2, … FROM table1, table2 WHERE table1.join_column = table2.join_column You must include a join condition for every link between 2 tables Join condition Guide to Oracle 10g

204 Inner Joins Example: SELECT s_name, f_name FROM student, faculty WHERE student.f_id = faculty.f_id; If you have N tables in the FROM clause, you must have (N - 1) join conditions Guide to Oracle 10g

205 Inner Joins If the tables have a single commonly named and defined column, you can use the NATURAL JOIN keywords to join the tables. See example figure 3-43 page 161. Example SELECT s_name, f_name FROM student NATURAL JOIN faculty; Note: No commas between table names, just the key words. No qualifiers are needed. Guide to Oracle 10g

206 Qualifying Field Names
If a field in the SELECT clause exists in multiple tables in the FROM clause, you must qualify the field name by prefacing it with either table’s name Guide to Oracle 10g

207 Process for Designing Complex Inner Join Queries
Identify all of the tables involved in the query, and label: Display fields Join fields Search fields Write the query List all display fields in the SELECT clause List all table names in the FROM clause List all join condition links in the WHERE clause List all search fields in the WHERE clause Guide to Oracle 10g

208 Process for Designing Complex Inner Join Queries
What happens if you omit a join condition in a multiple-table query? The output retrieves more rows than expected. (Cartesian product). See example page 166. Guide to Oracle 10g

209 Outer Joins Limitation of inner joins: Example:
some records may be omitted if corresponding records don’t exist in one of the tables Example: retrieve records for all students, along with their corresponding ENROLLMENT information Guide to Oracle 10g

210 Outer Joins Student 105 (Michael Connoly) does not have any ENROLLMENT records. So no information about 105 will be retrieved when using inner join. Guide to Oracle 10g

211 Outer Joins No records retrieved for Michael: Guide to Oracle 10g

212 Outer Joins To include records in first (inner) table, even when they do not have matching records in second (outer) table: place outer join marker (+) beside outer table name in join clause The (+) signals the DBMS to insert a NULL value for the columns in the outer table that do not have matching rows in the inner table. Guide to Oracle 10g

213 Outer Joins Outer join marker Guide to Oracle 10g

214 Self Joins Used to join a table to itself when the table has a foreign key that references a column in the same table. Guide to Oracle 10g

215 Self Joins To create a self-join, you need to create a table alias, which gives an alternate name to the table so you can create a join condition Syntax to create table alias in FROM clause: FROM table1 alias1, table2 alias2 Guide to Oracle 10g

216 Self Joins PARENT_PROJECT SUB_PROJECT Alias 2 PROJECT Alias 1
Guide to Oracle 10g

217 Self Join Example Note: the table alias is used in the select clause and in join conditions. NOT the table name. Guide to Oracle 10g

218 Inequality Joins Join created by placing making join condition satisfy an inequality condition(< , > , !=) Only makes sense when primary/foreign key values are not surrogate keys Guide to Oracle 10g

219 Inequality Joins Guide to Oracle 10g

220 Nested Queries Created when a subquery is nested within a main query
Main query: first query listed in SELECT command Subquery: retrieves one or more values that specify the main query’s search condition Guide to Oracle 10g

221 Nested Query Where Subquery Returns a Single Value
Syntax: SELECT column1, column2, … FROM table1, table2, … WHERE join conditions AND search_column1 = (SELECT column1 FROM table1, table2, … WHERE search and join conditions) Subquery that returns one value Guide to Oracle 10g

222 Nested Query Where Subquery Returns Multiple Values
Syntax: SELECT column1, column2, … FROM table1, table2, … WHERE join conditions AND search_column1 IN (SELECT column1 FROM table1, table2, … WHERE search and join conditions) Subquery that returns multiple values Guide to Oracle 10g

223 Using Set Operators in Queries
Performs set operations on outputs of two unrelated queries Both queries must have: same number of display fields corresponding display fields must have same data type Guide to Oracle 10g

224 Query Set Operators UNION: combines results, suppresses duplicate rows
UNION ALL: combines results, displays duplicates INTERSECT: finds matching rows MINUS: returns the difference between returned record sets Guide to Oracle 10g

225 Database Views Logical table based on a query
Does not physically exist in the database Presents data in a different format from underlying tables Uses: Security Simplifying complex queries Guide to Oracle 10g

226 Database Views CREATE VIEW view_name AS SQL_command; Creating a view:
Views can be queried just like tables: SELECT * FROM view_name; Guide to Oracle 10g

227 Simple Views Based on SQL query that retrieves data from only one table View can support all table DML operations: INSERT UPDATE DELETE Guide to Oracle 10g

228 Complex Views Based on query that retrieves data from multiple tables
Can only be used to support SELECT operations No DML operations supported Guide to Oracle 10g

229 Synonyms Alternate name for a table
Allows you to not have to preface table with owner’s username when you are querying a table that belongs to another user Guide to Oracle 10g

230 Public Synonyms Can only be created by a DBA Syntax:
CREATE PUBLIC SYNONYM synonym_name FOR owner_name.tablename; All users with privileges to use table can then use synonym instead of owner_name.tablename Guide to Oracle 10g

231 Private Synonyms You can create private synonyms for any tables that you have privileges to use Only you can use the synonym Syntax: CREATE SYNONYM synonym_name FOR table_name.table_name; Guide to Oracle 10g

232 Dynamic SQL Queries Queries that allow users to specify search conditions at runtime Approaches Substitution Values Runtime Variables Guide to Oracle 10g

233 Using Substitution Values
Created when search expression is prefaced with an ampersand (&) System then prompts user for value Guide to Oracle 10g

234 Using Runtime Variables
Runtime variable: variable defined in SQL*Plus environment Syntax: DEFINE variable_name = variable_value; You can then substitute the variable name for a query search condition value Guide to Oracle 10g

235 Using Runtime Variables
Example: Guide to Oracle 10g

236 Chapter 4: Introduction to PL/SQL
Guide to Oracle 10g

237 Lesson A Objectives After completing this lesson, you should be able to: Describe the fundamentals of the PL/SQL programming language Write and execute PL/SQL programs in SQL*Plus Execute PL/SQL data type conversion functions Display output through PL/SQL programs Manipulate character strings in PL/SQL programs Debug PL/SQL programs Guide to Oracle 10g

238 Introduction DB users use GUI applications to enter data into input boxes, and then click buttons to execute programs that perform DB functions. We will use the following utilities: Form builder Report builder To use these utilities effectively an understanding of PL/SQL is needed. PL/SQL is a procedural programming language that Oracle utilities use to manipulate DB data. Programming or scripting language concepts understanding is necessary. Guide to Oracle 10g

239 Fundamentals of PL/SQL
PL/SQL program combines SQL queries with procedural commands (if/then, loops). It is a full-featured programming language Executed using Oracle 10g utilities such as: SQL*Plus or Forms Builder It is an interpreted language Its commands are not a case sensitive. Inside single quotes are case sensitive.. ‘M’ != ‘m’ Semicolon ends each command It contains reserved words and built in functions. Guide to Oracle 10g

240 PL/SQL Command Capitalization Styles
Guide to Oracle 10g

241 PL/SQL Variables and Data Types
Variable names must follow the Oracle naming standard Strongly typed language: Explicitly declare each variable including data type before using variable Variable declaration syntax: variable_name data_type_declaration; Default value always NULL PL/SQL supports: scalar, composite, reference and LOB. Guide to Oracle 10g

242 Scalar Variables Reference single value
Data types correspond to Oracle 10g database data types VARCHAR2 CHAR DATE NUMBER Guide to Oracle 10g

243 General Scalar Data Types
Guide to Oracle 10g

244 Composite Variables Data Structure is a data object made up of multiple individual data elements Composite variable is a data structure contains multiple scalar variables Types: RECORD TABLE VARRAY Guide to Oracle 10g

245 Reference Variables Reference variables directly reference specific database column or row Reference variables assume data type of associated column or row %TYPE data declaration syntax: variable_name tablename.fieldname%TYPE; %ROWTYPE data declaration syntax: variable_name tablename%ROWTYPE; Guide to Oracle 10g

246 Reference Variables The (%TYPE) reference data type specifies a variable that references a single DB field. current_f_last FACULTY.F_LAST%TYPE; The current_f_last variable assumes a data type of VARCHAR2(30), because this is the data type of the f_last column in the FACULTY table. Guide to Oracle 10g

247 Reference Variables The (%ROWTYPE) reference data type creates composite variables that reference the entire data record. Faculty_row FACULTY%ROWTYPE; The variable faculty_row references all of the columns in the FACULTY table, and each column has the same data type as its associated DB column. Guide to Oracle 10g

248 LOB Data Types It declares variables that reference binary or character data objects up to 4 GB. LOB values in PL/SQL programs must be manipulated using special package called DBMS_LOB. Guide to Oracle 10g

249 PL/SQL Program Blocks Declaration section (DECLARE)
Optional (variable declaration) Execution section (BEGIN) Required (Program statements) Exception section (EXCEPTION) Optional (Error handling statements) Comment statements Enclosed within /* and */ Two hyphens (--) for a single line comment END; Guide to Oracle 10g

250 PL/SQL Arithmetic Operators in Describing Order of Precedence
Guide to Oracle 10g

251 Assignment Statements
Assigns value to variable Operator := Syntax variable_name := value; String literal must be enclosed in a single quotation marks. Guide to Oracle 10g

252 Assignment Statements
You can use the := in the declaration section to give initial values. s_id NUMBER := 100; You can use DEFAULT instead: s_id NUMBER DEFAULT 100; If NULL value is used in an assignment statement with arithmetic operation, the result is always NULL. Guide to Oracle 10g

253 Executing a PL/SQL Program in SQL*Plus
Create and execute PL/SQL program blocks within variety of Oracle 10g development environments: SQL *Plus Form Builder Report Builder Guide to Oracle 10g

254 Displaying PL/SQL Program Output in SQL*Plus
PL/SQL output buffer Memory area on database server Stores program’s output values before they are displayed to user Buffer size should be increased before output is displayed: SET SERVEROUTPUT ON SIZE buffer_size Default buffer size 2000 bytes If the output is more than buffer_size, error apperas. Guide to Oracle 10g

255 Displaying PL/SQL Program Output in SQL*Plus (continued)
Display program output DBMS_OUTPUT.PUT_LINE('display_text'); Display maximum of 255 characters of text data. More than 255 characters gives an error. Example: s_name := ‘Ahmed Mahmoud’; DBMS_OUTPUT.PUT_LINE(s_name); Guide to Oracle 10g

256 Writing a PL/SQL Program
Write PL/SQL program in Notepad or another text editor Copy and paste program commands into SQL*Plus Press Enter after last program command Type front slash ( / ) (to instruct the interpreter to execute the code) Then press Enter again Guide to Oracle 10g

257 Writing a PL/SQL Program (continued)
Good programming practice Place DECLARE, BEGIN, and END commands flush with left edge of text editor window Indent commands within each section Guide to Oracle 10g

258 PL/SQL Program Commands
Output: Today’s data is 18-OCT-07 PL/SQL procedure successfully completed If no output appears use: SQL> set serveroutput on Guide to Oracle 10g

259 PL/SQL Data Conversion Functions
Implicit data conversions Interpreter automatically converts value from one data type to another (the command DBMS_OUTPUT.PUT_LINE(todays_date), the interpreter automatically converted the todas_date DATE variable to a text string for output). If PL/SQL interpreter unable to implicitly convert value error occurs Explicit data conversions Convert variables to different data types Using built in data conversion functions Guide to Oracle 10g

260 PL/SQL Data Conversion Functions of PL/SQL
Guide to Oracle 10g

261 Manipulating Character Strings with PL/SQL
Character data value Consists of one or more characters Concatenating Joining two separate strings Parse Separate single string consisting of two data items separated by commas or spaces Built in functions to concatenate and parse strings in SQL*Plus are as follows: Guide to Oracle 10g

262 Concatenating Character Strings
Double bar Operator || Syntax: new_string := string1 || string2; Example: Full_name := ‘Qusai’ || ‘ ‘ || ‘Abuein’ You must convert NUMBER and DATE data type variables (TO_CHAR)into a string before concatenating it. Guide to Oracle 10g

263 Removing Blank Leading and Trailing Spaces from Strings
LTRIM function Remove blank leading spaces string := LTRIM(string_variable_name); RTRIM function Remove blank trailing spaces string := RTRIM(string_variable_name); Guide to Oracle 10g

264 Finding the Length of Character Strings
LENGTH function syntax string_length := LENGTH(string_variable_name); Space is included wherever it appears. DBMS_OUTPUT.PUT_LINE(LENGTH('Today''s date is ')); Gives 20. Guide to Oracle 10g

265 Character String Case Functions
Modify case of character strings Functions and syntax: string := UPPER(string_variable_name); string := LOWER(string_variable_name); string := INITCAP(string_variable_name); Guide to Oracle 10g

266 Parsing Character Strings
INSTR function Searches string for specific substring If substring is found, the starting position of it within the original_string is returned as integer value. Otherwise, zero is returned. Syntax: start_position := INSTR(original_string, substring); start_positioin should be integer data type. Guide to Oracle 10g

267 Parsing Character Strings
SUBSTR function Extracts specific number of characters from character string starting at given point Syntax: extracted_string := SUBSTR(string_variable, starting_point, number_of_characters); To parse a string, usually INSTR is used to find delimiter and then use the SUBSTR. Example page 206, 207. Guide to Oracle 10g

268 Debugging PL/SQL Programs
Syntax error Occurs when command does not follow guidelines of programming language Generate compiler or interpreter error messages Logic error Does not stop program from running Results in incorrect result Guide to Oracle 10g

269 Program with a Syntax Error
Guide to Oracle 10g

270 Program with a Logic Error
Guide to Oracle 10g

271 Finding Syntax Errors Often involve: Interpreter
Misspelling reserved word Omitting required character in command Using built-in function improperly Interpreter Flags line number and character location of syntax errors May actually be on preceding line Displays error code and message Guide to Oracle 10g

272 Finding Syntax Errors (continued)
Comment out program lines To find error Cascading errors are called so when One syntax error can generate many more errors Fix the first error and rerun the program. Do not fix next errors before rerunning the program. Guide to Oracle 10g

273 Finding Logic Errors Caused by:
Not using proper order of operations in arithmetic functions Passing incorrect parameter values to built-in functions Creating loops that do not terminate properly Using data values that are out of range or not of right data type Guide to Oracle 10g

274 Finding Logic Errors (continued)
Debugger Program that enables software developers to pause program execution and examine current variable values Best way to find logic errors SQL*Plus environment does not provide PL/SQL debugger Use DBMS_OUTPUT to print variable values Guide to Oracle 10g

275 Lesson A Summary PL/SQL data types: Program block Scalar Composite
Reference LOB Program block Declaration Execution Exception Guide to Oracle 10g

276 Lesson B Objectives After completing this lesson, you should be able to: Create PL/SQL decision control structures Use SQL queries in PL/SQL programs Create loops in PL/SQL programs Create PL/SQL tables and tables of records Use cursors to retrieve database data into PL/SQL programs Guide to Oracle 10g

277 Lesson B Objectives (continued)
Use the exception section to handle run-time errors in PL/SQL programs Guide to Oracle 10g

278 PL/SQL Decision Control Structures
Sequential processing Processes statements one after another Decision control structures Alter order in which statements execute Based on values of certain variables Guide to Oracle 10g

279 IF/THEN Syntax: Condition IF condition THEN
commands that execute if condition is TRUE; END IF; Condition Expression evaluates to TRUE or FALSE If TRUE commands execute See Examples pages 221,222 Guide to Oracle 10g

280 PL/SQL Comparison Operators
Do not get confused with the equal (=) sign and the assignment (:=) operator Guide to Oracle 10g

281 IF/THEN/ELSE Syntax: Evaluates ELSE command if condition FALSE
IF condition THEN commands that execute if condition is TRUE; ELSE commands that execute if condition is FALSE; END IF; Evaluates ELSE command if condition FALSE See example pages 223 Guide to Oracle 10g

282 Nested IF/THEN/ELSE Placing one or more IF/THEN/ELSE statements within program statements that execute after IF or ELSE command Important to properly indent program lines See example page 224 Guide to Oracle 10g

283 IF/ELSIF Syntax: Note there is no E fire IF in ELSIF, and no spaces.
IF condition1 THEN commands that execute if condition1 is TRUE; ELSIF condition2 THEN commands that execute if condition2 is TRUE; ... ELSE commands that execute if no conditions TRUE; END IF; Note there is no E fire IF in ELSIF, and no spaces. See example page 225 Guide to Oracle 10g

284 Logical Operators AND, OR, and NOT
Create complex expressions for decision control structure condition AND Expressions on both sides of operator must be true for combined expression to be TRUE OR Expressions on either side of operator must be true for combined expression to be TRUE Guide to Oracle 10g

285 Logical Operators AND, OR, and NOT (continued)
Order of evaluation: NOT (evaluated first) AND OR Guide to Oracle 10g

286 Evaluating AND and OR in an Expression
Guide to Oracle 10g

287 Using SQL Queries in PL/SQL Programs
Use SQL action query Put query or command in PL/SQL program Use same syntax as execute query or command in SQL*Plus Can use variables instead of literal values to specify data values Ex: curr_f_name := “Ahmad’ We need to insert ‘Ahmad’ into a column S_FIRST INSERT INTO student (s_first) VALUES (curr_f_name); Ex: WHERE s_first = curr_f_name; PL/SQL Command Guide to Oracle 10g

288 Using SQL Commands in PL/SQL Programs
Guide to Oracle 10g

289 Loops Systematically executes program statements
Periodically evaluates exit condition to determine if loop should repeat or exit Pretest loop Evaluates exit condition before any program commands execute Posttest loop Executes program commands before loop evaluates exit condition for first time In PL/SQL there are FIVE loop structures. Guide to Oracle 10g

290 The LOOP...EXIT Loop This kind of loop can be either Pretest or posttest Syntax: LOOP [program statements] IF condition THEN EXIT; END IF; [additional program statements] END LOOP; Guide to Oracle 10g

291 The LOOP...EXIT Loop LOOP keyword signals the beginning of the loop.
If the IF/THEN decision structure is the first code in the loop, it is a pretest loop. If the IF/THEN decision structure is the last code in the loop, it is a posttest loop. See Example page 233. Guide to Oracle 10g

292 The LOOP...EXIT WHEN Loop Can be either a Pretest or posttest Syntax:
program statements EXIT WHEN condition; END LOOP; See example page 234. Guide to Oracle 10g

293 The WHILE...LOOP It is a Pretest loop that test the condition before it execute any program statements. Syntax: WHILE condition LOOP program statements END LOOP; See example page 235. Guide to Oracle 10g

294 The Numeric FOR Loop In the previous LOOP structures we had to increment the counter variable. The numeric FOR does not require explicit counter increment Automatically increments counter Syntax: FOR counter_variable IN start_value ... end_value LOOP program statements END LOOP; Start_value and end_value must be integer. The increment is always done by 1. See example page 236. Guide to Oracle 10g

295 Cursors FOR Loop Pointer to memory location on database server that the DBMS uses to process a SQL query Use to: Retrieve and manipulate database data from the tables into PL/SQL programs Types: Implicit Explicit Guide to Oracle 10g

296 Implicit Cursors Context area Active set Implicit cursor
Is a memory location on the DB server contains information about query, such as the number of rows the query processed. Created by INSERT, UPDATE, DELETE, or SELECT Active set Set of data rows that query retrieves using SELECT Implicit cursor Is a Pointer to the context area. Called so because you do not need explicit command to create it. Guide to Oracle 10g

297 Implicit Cursors (continued)
Can be used to assign output of SELECT query to PL/SQL program variables: When query will return only one record If the query returns more than one record or zero records, an error occurs. Guide to Oracle 10g

298 Implicit Cursors (continued)
Syntax: SELECT field1, field2, ... INTO variable1, variable2, ... FROM table1, table2, ... WHERE join_conditions AND search_condition_to_retrieve_1_record; The value of field1 is assigned to variable1, field2 to variable2 and so on. Data types of field1, field2 and variable1, variable2 must be the same. Guide to Oracle 10g

299 Implicit Cursors (continued)
Useful to use %TYPE reference data type To declare variables used with implicit cursors Syntax: var_name tablename.fieldname%TYPE Ex: curr_f_last faculty.f_last%TYPE Ex: Page 239 (fig. 4-26) Error “ORA-01422: exact fetch returns more than requested number of rows” . Ex. Page 239 (fig. 4-27). Implicit cursor query tried to retrieve multiple records Error “ORA : no data found. Ex. Page 240 (fig.4-28). If one of these errors occur, you should modify the query to retrieve only one record, or use Explicit cursor. Guide to Oracle 10g

300 Explicit Cursors Retrieve and display data in PL/SQL programs for query that might: Retrieve multiple records Return no records at all Steps for creating and using explicit cursor Declare cursor Open cursor Fetch data rows Close cursor Guide to Oracle 10g

301 Explicit Cursors (continued)
Declare explicit cursor syntax: by declaring an explicit cursor, you create a memory location on the DB server that processes a query and stores the retrieved records . Syntax: CURSOR cursor_name IS select_query; cursor_name: Any valid PL/SQL name. select_query: The query that retrieves the data values. Open explicit cursor syntax: by doing so the interpreter checks for syntax error, upon correct it translate the query into machine-language format. The system then creates the memory location that stores the active set (contains the retrieved data using SELECT) (see slide 61) . Syntax OPEN cursor_name; Guide to Oracle 10g

302 Explicit Cursors (continued)
Fetch command is used to retrieve the data from the DB into the active set, one row at a time. Because a query might return several rows, you execute the FETCH command within a (LOOP…EXIT WHEN) loop: Syntax: LOOP FETCH cursor_name INTO variable_name(s); EXIT WHEN cursor_name%NOTFOUND; Cursor_name is name of the cursor defined previously. Variable_name(s) represents either a single variable or a list of variables that receives data from the cursor’s SELECT query. (every retrieved column from the DB table is associated with a program variable variable, %TYPE or %ROWTYPE) Guide to Oracle 10g

303 Explicit Cursors (continued)
Active set pointer is created when processing explicit cursor that: Indicates memory location of the next record retrieved from database After the last record of the query is executed, that pointer points to an empty record. The condition (EXIT WHEN cursor_name%NOTFOUND) guarantees the exit when the pointer points to an empty record. Guide to Oracle 10g

304 Explicit Cursors (continued)
Close cursor syntax: CLOSE cursor_name; You should close a cursor after processing all records so as the memory and other resources are available to the system for other tasks. The system automatically closes the cursor when the program ends, if you forget to do so. Guide to Oracle 10g

305 Processing Explicit Cursors Using a LOOP...EXIT WHEN Loop
Often used to process explicit cursors that retrieve and display database records Use %TYPE variable to display explicit cursor values (See example Figure 4-29 page 243) Use %ROWTYPE variable to display explicit cursor values (See example Figure 4-30 page 244) Guide to Oracle 10g

306 Processing Explicit Cursors Using a Cursor FOR Loop
Make it easier than LOOP...EXIT WHEN to process explicit cursors. For Loop automatically: Opens cursor Fetches records Closes cursor Guide to Oracle 10g

307 Processing Explicit Cursors Using a Cursor FOR Loop (continued)
Syntax: FOR variable_name(s) IN cursor_name LOOP processing commands END LOOP; See example Figure 4-31 page 245. Guide to Oracle 10g

308 Explicit Cursors Using a Cursor FOR Loop, LOOP...EXIT WHEN
The cursor variable can be referenced outside the Loop … Exit When. While can not be referenced outside the For Loop. Guide to Oracle 10g

309 Handling Runtime Errors in PL/SQL Programs
Pl/SQL supports Exception handling, that is: Programmers place commands for displaying error messages and Give users options for fixing errors in program’s exception section (Optional section in a PL/SQL program block. Page 195) Runtime errors Cause program to fail during execution Exception section is used to handle runtime error. Unwanted event. See Example Figure Page 247 (runtime error). Guide to Oracle 10g

310 Handling Runtime Errors in PL/SQL Programs (cont.)
An exception or unwanted event is raised when a runtime error occurs. The control is transferred to the exception section, where the exception handler has the following options: Correct error without notifying user of problem Inform user of error without taking corrective action Correct and inform Inform the user and allow him to decide what action to take. After exception handler executes Program ends Guide to Oracle 10g

311 Handling Runtime Errors in PL/SQL Programs (cont.)
There are three kinds of exceptions: Predefined Undefined User defined Guide to Oracle 10g

312 Predefined Exceptions
Most common errors that occur in programs PL/SQL language: Assigns exception name Provides built-in exception handler for each predefined exception System automatically displays error message informing user of the nature of the problem One can create exception handlers to display alternate error messages for predefined exception Guide to Oracle 10g

313 Common PL/SQL Predefined Exceptions
Guide to Oracle 10g

314 Exception Handler Syntax
The syntax to write an alternate error messages for predefined handler. Guide to Oracle 10g

315 Exception Handler Syntax
exception_name1, exception_name2,… refer to the name of the predefined exception (table 4-10). Exception handler commands represent commands that display the error message. WHEN OTHERS THEN clause is a handler presents a general message to describe errors that do not have specific exception handlers. See examples 4-34 and Pages 249, 250. Guide to Oracle 10g

316 Exception Handler Syntax
When using alternate error message, such as in the example 4-35, which handles only the NO_DATA_FOUND. An unanticipated error might occur. That way no handler exists to handle such unanticipated errors. For that reason it is helpful to use the WHEN OTHERS exception handler too, so as to display messages for that situation. To do this, use SQLERRM built-in function (SQL ERRor Message). That function returns a string that contains the most recent error code and its description. First define a varchar2 variable of length 512 to assign it the error message: error_message := SQLERRM; See example Figure 4-36 page 251. Guide to Oracle 10g

317 Undefined Exceptions Less common errors Do not have predefined names
One must explicitly declare exception in program’s declaration section and Associate the new exception with a specific Oracle error code then Create an exception handler in the exception section Using the same syntax as for predefined exceptions Guide to Oracle 10g

318 Syntax of Undefined Exceptions
DECLARE e-exception_name EXCEPTION; PRAGMA EXCEPTION INIT(e-exception_name, -Oracle_error_code); e-exception_name represents name you assign to the exception. PRAGMA EXCEPTION INIT: a command associates your exception name with a specific Oracle error code. The hyphen (-) must precede the Oracle_error_code. See for example Figure 4-37, the code is –2291. See example Figure 4-38 on undefined exception, page 253. Guide to Oracle 10g

319 User-defined Exceptions
User-defined exceptions do not raise Oracle runtime error. BUT Require exception handling to: Enforce business rules (special rules of a company, example page 253. Rule: one can only delete grades with values NULL. Other grades can not be deleted. If a user tries to delete a grade that its value is not NULL, the program should raise an exception and display a message) or Ensure the integrity of database Guide to Oracle 10g

320 General Syntax for Declaring, Raising, and Handling a User-defined Exception
Guide to Oracle 10g

321 See example Figure 4-40, page 255.
General Syntax for Declaring, Raising, and Handling a User-defined Exception To raise the exception, you must use the IF/THEN, which evaluates the exception condition (grade IS NOT NULL). If the condition is TRUE, the RAISE command is executed and raises the exception (transfer execution to the exception section). The exception handler executes and displays the error-handling messages. See example Figure 4-40, page 255. Guide to Oracle 10g

322 Lesson B Summary Decision control structures: Loop IF/THEN
IF/THEN/ELSE IF/ELSIF Loop Repeats action multiple times until it reaches exit condition Five types of loops Guide to Oracle 10g

323 Lesson B Summary (continued)
Cursor Pointer to memory location that DBMS uses to process SQL query Types: Implicit Explicit Exception handling Three exception types Guide to Oracle 10g

324 Enhanced Guide to Oracle 10g
Chapter 5: Introduction To Form Builder

325 Forms Why Do We Use Form Builder? Why Don’t We Use SQL Only?!

326 Forms Application with a graphical user interface that looks like a paper form Used to insert, update, delete and view database data

327 Primary Form Uses Viewing/retrieving records
Inserting/updating/deleting records Counting the number of records a query will retrieve

328 Data Block Form Is a form associated with a specific Oracle database table System automatically creates: Text fields associated with table fields Programs for inserting, modifying, deleting, and viewing data records

329 Data Block Forms ORACLE 10g forms are displayed in a web browser as a web page. They appear in the Forms Services Window within the browser window. The form specification is translated into Java Applet (those are displayed in web browsers) using a Web server process called OC4J Instant (details: page 264, next slide too). They are Dynamic Web Pages.

330 Steps of running the form
Design the form and write its code (.fmb file) Compile the form (.fmx file) When you run the form: OC4J Instance process converts the compiled file into java applet Java applet form starts on the web browser

331 Using a Data Block Form A block is a group of related form items (text fields, option buttons,…). A data block is a specific DB table, and contains objects (text fields, option buttons) that display values from the table’s data fields. A single-block form: is the form that displays data from only one table. A multiple-block form: is the form that displays data from multiple DB tables.

332 Using a Data Block Form To start Form Builder:
Start, All programs, Oracle Developer Suit-OraHome, Forms Developer, Forms Builder Open an existing for (.fmb) or design yours and save it (the path name or the form name should not contain spaces). To run the form, click Program on the menu bar, Run Form. If you are asked to install the Jinitiator, click yes and accept all default values. Jinitiator application iniitializes the Java applet in the web browser.

333 Expected Errors If the error “FRM-90928” appears, it means that the path name or the form name contains space. If the web page does not appear and the browser diplays the characters or similar. Then the form builder should be configured correctly to use your web browser. (see page 266 to know how to configure it).

334 Form Modes When the form is running in the Forms Services window in the web browser it can be one of two modes: Normal Mode You can view records and sequentially step through records and change data. Enter Query Mode You can enter search parameters in form fields and then retrieve the associated records To place the form in Enter Query mode, click the Enter Query button on the toolbar. Execute the query or cancel it to return to Normal mode.

335 Inserting New Records In Normal mode, click the Insert Record button to insert a new blank record Type the data values in the form fields Click the Save button to save the values in the database

336 Retrieving Records Click the Enter Query button to place the form in Enter Query mode Type a search condition Click the Execute Query button to retrieve selected records If you click , do not enter a search condition, and then click , all table records will be retrieved

337 Form Search Types Exact search: only retrieves records that exactly match the entered search condition Restricted search: retrieves records that fall within a range of values

338 Restricted Search Operators
_: wildcard replacing a single character %: wildcard replacing multiple characters >, <: greater than, less than >=, <=: greater than or equal to, less than or equal to <> or !=: not equal to

339 Scrolling Through Retrieved Records
To view the next record, click the Next Record button To view the previous record, click the Previous Record button

340 Updating and Deleting Records
Retrieve the record to be updated or deleted To update, change the data value and click the Save button To delete, click the Remove Record button

341 Data Block Form File Types
.fmb Form design file, used by form programmer in Form Builder .fmx Form executable file, run by form users

342 Form Components Form module: form application Form window
Title bar on top Horizontal and vertical scrollbars Can be resized, maximized, minimized

343 Form Components Canvas Block Form items
Surface that displays form items Block Object that contains form items Form items Command buttons, radio (option) buttons, text items Items in the same block can appear on different canvases

344 Form Components Window Canvas Block of items Name Cash Check
Credit Card

345 Object Navigator Forms Builder Toolbar.
Form Module. See Page 276, next slde. Hierarchical Display.

346 To create a new Form module or Data block..

347 Creating a Data Block Form
Steps: 1. Create the data block using the Data Block Wizard 2. Create the form layout using the Layout Wizard

348 Data Block Wizard Welcome page Type page Table page Finish page
Select table or view on which to base the block source Table page Select table associated with form Enforce Integrity Constraint Check Box Finish page Option to use the Layout Wizard to automate creating the layout

349 Layout Wizard Canvas page Data Block page Items page Style page
Select the canvas where the block is displayed Data Block page Select the fields that are displayed on the layout Items page Specify the column labels, heights and widths Style page Specify to create a form- or tabular-style layout

350 Layout Styles Form style Tabular style
One record appears on the form at a time Tabular style Multiple records display on the form in a table

351 Form Builder Wizards Are Re-entrant
You can select a block or layout, then re-enter it and modify its properties using the Wizard A Wizard is in re-entrant mode when its pages appear as tabs

352 Form Builder Object Navigator Window
Shows form objects Allows developer to access form objects Object Navigator has 2 views Ownership view: shows form objects as a flat list (the form is presented as a top-level object, and then lists all form object nodes on the next level) . (fig. 5-8, slide 23) Visual view: hierarchical relationships between objects ( form objects contain other objects: a form contains windows, a window contains canvases and a canvas contains data blocks).(fig. 5-27, next slide) Details about ownership and visual views is in page 300.

353

354 Guidelines For Configuring Form Windows
Change the window title Allow user to minimize the window Do not allow the user to maximize the window Do not allow the user to resize the window Include horizontal and vertical scrollbars if items appear beyond window boundaries Make the form window fill the Forms Runtime window

355 Configuring Form Windows
Title Minimize/ Maximize buttons Window size

356 Example: create a Data Block using WIZARD
Click on the Data Block node under the MODULE form node. Click the + sign or choose create from Edit on the menu bar. The following window appears: Choose the first option, now Then the Ok  A Welcome page might appear, if so click next The wizard window appears as shown next slide:

357

358 Example: create a Data Block using WIZARD
Make sure the table or view is selected, now. Then NEXT The tables window appears so as to choose the table from your schema, which the data block is based on. You might need to connect to the DB, if you are not doing yet. Choose the connect button or connect from file on the menu bar. Select the table, pay attention to the user. After that choose the field you want to show. Type the data block name. Then choose “create the data block, and then call the layout wizard, then FINISH.

359 Example: create a Data Block using WIZARD
The form layout specifies how a given form looks to the user. So a welcome window might appear, click next. Then a Canvas (the area where the form objects are located) window appear, choose the canvas and its type. For details about the types refer to page 285. The Data block page appear so you can choose the fields that will be displayed in the form. Fig Then the items page appears, where the specifications and labels (prompts) can be determined.

360 Example: create a Data Block using WIZARD
You can change the prompts (labels that appears next to each field). Then choose whether the layout style is FORM or Tabular. If form is chosen, then determine the title that appears on the frame of the data block, the number of rows that appear in the form style is always one row at a time. If the tabular is chosen, then number can be more. The distance between record is determined in a tabular case. Choose whether to display the scroll bar. Finish. The window should appear as in next slide:

361

362 Example: create a Data Block using WIZARD
You can import a static image to make your form looks better: Click on the layout editor window shown in the previous slide. From EDIT choose import  image. Select the image you like. Adjust its place on the window. To run the form so as to see the data of the table: Run the form using the button or from Program on the menu bar choose run form. Important: If the “FRM-10142” error appears, then run the OC4J instant of the form If the HTML code appears instead of the form on your browser then do the following” from IE chose tools  Internet Options  Advanced  Look for Security value then Check the “allow active controls to run in files on my computer”.

363 Lesson B

364 Creating a Form Based on a Database View
View can be derived from one or more database tables Form based on a view only allows you to display data from table(s) Form could be used to insert, update, or delete data if the view is a simple view only. How to do that ? Select Views from Figure 5-12, see slide 35 when you create the form using the wizard.

365 Modifying Form Properties
Every form object has a Property Palette that allows you to configure form and its objects properties (page 322) How to open the property palette? From the Object navigator chose windows node, select your window and right click the mouse, choose property palette. OR: On the layout editor, right click and then select property palette. OR: See page 323 for other two ways. Context bar Property Nodes Property List

366 Intersection Property Palette
Used to change property of several items to the same value (page 328) Select the objects together and open the property palette. Intersection/Union button on the tool bar appears as When the objects have different values, it appears as *****, and the property node appears with a ? Before it.

367 Frame Properties frame
The frame is that encloses a data block’s items. Its update Layout can be: Automatically Frame items are automatically repositioned based on their order in the Data Blocks list when you move or resize a frame, or modify the form layout using the Layout Wizard in reentrant mode Manually Items are automatically when layout is modified in Layout Wizard in reentrant mode Items are not repositioned if you move or resize the frame Locked Items are never automatically repositioned frame

368 Multiple-Table Forms Examples:
Data block forms can display data from multiple tables that have a master-detail relationship in which Master record can have multiple related (detail) records through foreign key relationship. Examples: One FACULTY record can have multiple related STUDENT records. The FACUTLY record is the master record, because a faculty member can have many student records, but a student can have only one related faculty record. One CUSTOMER might have multiple CUST_ORDER records

369 Multiple-Table Forms When creating a form that contains a master-detail relationship, you always use the Data Block Wizard to create the master block, which is the block that displays the master records first. Then start the wizard a second time, and create the detail block, which displays the detail records. When creating the detail block, the master-detail relationship should be specified in the wizard on a page called Master_Detail page. That page appears only when you create a data block that already contains one or more data blocks.

370 Master-Detail Forms Master block Detail block

371 Creating a Master-Detail Form
Create the master block first Specify the relationship on the Data Block Wizard Master-Detail page of the detail block

372 Complex Master-Detail Relationships
A master block can have multiple detail blocks An item can be in multiple customer orders, and have multiple shipment records A student has an advisor and also enrolled in courses. page 342. A detail block can be a master block in a second master-detail relationship A customer can have multiple CUST_ORDER records One CUST_ORDER record can have multiple ORDER_LINE records A faculty member can have many students and a student can be enrolled in many classes. Page 342.

373 Complex Master-Detail Relationship Example

374 Formatting Text Items Specify desired format mask in text item Format Mask property If format mask makes value wider than text item Data Width property, data appears as ##### E.g: make the format mask for the empno field in the form builder: 99”- - “ 99 and make the data length for the field 4.

375 Formatting Character Text Items
Place embedded characters in double quotes

376 Format Mask Examples Value Format Mask Result 7945 999 ###
### $ $ ”-” SYSDATE Day-MON-YY Friday-NOV-06

377 Lesson C

378 Form Triggers PL/SQL procedure that runs in response to a user or system action Clicking a button Loading a form Exiting a form Triggers can be associated with: An entire form (form level) A block (block level) A specific form item (item level)

379 Using Form Triggers Creating a trigger:
select the form or form item event type the trigger code Referencing a form item in PL/SQL code: :block_name.item_name Triggers are compiled before a form is run

380 Using Sequences in Forms
Create a block-level WHEN-CREATE-RECORD trigger Trigger PL/SQL code: SELECT sequence_name.NEXTVAL INTO :block_name.item_name FROM DUAL;

381 Form Lists of Values (LOVs)
List of legal values that can be selected for use in a form field LOV command button LOV display

382 Creating an LOV Using the LOV Wizard
Use the LOV Wizard to: Specify the LOV display records using a SQL query Format the LOV display Attach the LOV to a form text item Change the LOV and record group name in the Object Navigator

383 Opening the LOV Display
Place the insertion point in the text item to which the LOV is attached Press CTRL+L, or from Edit menu of the form choose the option ‘Display List’

384 Creating a Command Button to Open the LOV Display
Create a command button on the canvas Iconic button Displays an icon image from an .ico file Complete path to .ico file must be specified in button’s ICON property

385 LOV Command Button Trigger
Create a trigger for the button that does the following: Places the form insertion point in the text item to which the LOV is attached: GO_ITEM(‘IN_VID’); Executes the LIST_VALUES command: LIST_VALUES;

386 Alternate Form Input Items
Radio buttons Check boxes

387 Radio Buttons Limits user to one of two or more related, mutually exclusive choices

388 Radio Groups Related radio buttons are part of a radio group
Individual related radio buttons

389 Creating a Radio Group Create the form using the Data Block and Layout Wizards Open the item Property Palette, and change the Item Type value to Radio Group Draw and format the radio buttons on the canvas Modify the radio button properties Modify the radio group properties

390 Important Radio Button Properties
Name: how the button is referenced within the form Label: description that appears next to the button on the canvas Radio Button Value: associated data value in the database

391 Important Radio Group Properties
Name: how the radio group is referenced within the form Initial Value: data value of the radio button within the radio group that is selected when the form first appears

392 Check Boxes Used to represent fields that can have one of two values
Check box caption is interpreted as TRUE or FALSE If checked, caption is true If cleared, caption is false

393 Check Box Example

394 Creating a Check Box Create the form using the Data Block and Layout Wizards Open the item Property Palette, and change the Item Type value to Check Box Modify the item properties

395 Important Check Box Properties
Label: description that appears next to the check box on the canvas Value when Checked: data value of the item when the box is checked Value when Unchecked: data value of the item when the box is checked Check Box Mapping of Other Values: check box status when form first opens, or when new blank record is added

396 Thank you.

397 Enhanced Guide to Oracle10g
Chapter 6: Creating Custom Forms

398 Data Block and Custom Forms
Data block form Based on data blocks that are associated with specific database tables Reflect the structure of the database Custom form Based on control blocks that process data from multiple tables Reflect business processes rather than the database structure

399 Creating a Custom Form Create the form
Create the form window and canvas manually Create a control block Data block that is not associated with a specific table Contains form items that you manually draw on the canvas Create form triggers to process data

400 Form Triggers Code that is associated with a form object and an event
Can contain SQL INSERT, UPDATE, DELETE, and SELECT commands Referencing form text item values in triggers: :block_name.item_name

401 Program Units Self-contained programs
Can be called from PL/SQL triggers Used to make triggers more modular, and reuse code within triggers

402 Practice1 Create a custom form that has:
Employee Name Employee Salary Department Name Create a LOV to retrieve block records Use triggers to retrieve block records Create a button that calls a program unit to clear the block.

403 Referencing System Date and Time Values in Forms
System Variable Return Value $$DATE$$ Current operating system date $$TIME$$ Current operating system time $$DATETIME$$ Current operating system date & time $$DBDATE$$ Current DB server date $$DBTIME$$ Current DB server time $$DBDATETIME$$ Current DB server date & time

404 Form Triggers Categories Block processing Interface event
Master-detail processing Message handling Navigational Query time Transactional Validation

405 Trigger Timing PRE- POST- ON-, WHEN-, KEY-
Fires just before associated event occurs POST- Fires just after associated event occurs ON-, WHEN-, KEY- Fires immediately, in response to specific user actions, such as key presses

406 Trigger Scope Defines where an event must occur to make the trigger fire Trigger scope includes the object to which the trigger is attached, as well as all objects within that object Form-level: fires when event occurs within any block or item in the form Block-level: fires when event occurs within any item in the form Item-level: fires only when event occurs within that item

407 Trigger Execution Hierarchy
If 2 related objects have the same trigger, the lower-level object’s trigger fires instead of the higher-level one. Form & block, block’s trigger fires Block & item, item’s trigger fires You can specify a custom execution order using the Execution Hierarchy property of the trigger.

408 Navigational Triggers
External navigation: occurs when user causes form focus to change Internal navigation: occurs as a result of internal form triggers that fire in response to external navigation events

409 Triggers That Fire at Form Startup
Result on User Screen Display Triggers Fired User Action 3 2 1 Form appears, but with no data visible PRE-FORM PRE-BLOCK User starts form 4 5 WHEN-NEW-FORM-INSTANCE WHEN-NEW-BLOCK-INSTANCE WHEN-NEW-RECORD-INSTANCE WHEN-NEW-ITEM-INSTANCE Form is available for use

410 Triggers That Fire as a Result Of External Navigation
Result on User Screen Display Triggers Fired User Action User places the insertion point in a text item Insertion point appears in item WHEN-NEW-ITEM-INSTANCE User clicks the Next Record button Next record appears WHEN-NEW-RECORD-INSTANCE WHEN-NEW-ITEM-INSTANCE

411 Triggers That Fire When a Form Closes
Result on User Screen Display User Action Triggers Fired User closes the Forms Runtime window POST-BLOCK POST-FORM Forms Runtime window closes

412 Practice2 Create a department data block. Create an Update button.
Create a Cancel button that uses a procedure.

413 Directing External Navigation
Form tab order is based on item order in Object Navigator block list Form tab order

414 Moving to a Specific Form Item
GO_ITEM(‘block_name.item_name’); Do not write colon(:) before the block name in this commnd. E.g: GO_ITEM(‘emp.sal’); Other navigational instructions: GO_BLOCK(‘block_name’) GO_FORM(‘form_name’)

415 Oracle Error Message Severity Levels
5: informative message 10: informative message advising user of procedural error 20: condition that keeps trigger from working correctly 25 condition that keeps form from working correctly >25: extreme severity

416 Suppressing Lower Level System Messages
Set :SYSTEM.MESSAGE_LEVEL variable to a higher level in PRE-FORM trigger :SYSTEM.MESSAGE_LEVEL := 25;

417 Providing User Feedback in Forms
Message Text in message line at bottom of form Informational only; user doesn't have to respond Alert Dialog box Allows user to choose different ways to proceed

418 Messages Syntax: MESSAGE(‘message text’); Message

419 Alerts Form-level object Object properties define alert appearance
Message Title Style icon Buttons

420 Code for Displaying an Alert
DECLARE alert_button NUMBER; BEGIN alert_button := SHOW_ALERT('alert_name'); IF alert_button = ALERT_BUTTON1 THEN program statements for first button; ELSE program statements for second button; END IF; END;

421 Avoiding User Errors Make primary and foreign key text items non-navigable (How?) When user moves form focus to primary or foreign key text item, move focus to alternate form item (How?)

422 How to make nonnavigable item?
Set the text item property Keyboard Navigable to NO Use When New Item Instance or When Mouse Up triggers to make internal navigation from the nonnavigable item.

423 Trapping Runtime Errors
Create an ON-ERROR event trigger Form-level trigger Executes whenever an FRM- or ORA- error occurs -FRM errors: generated by Forms Runtime -ORA errors: generated by database

424 Form Procedures That Return System Error Information
DBMS_ERROR_CODE: The most recent -ORA error number. (Negative Number) DBMS_ERROR_TEXT: -ORA error message and number. ERROR_CODE: The most recent FRM error number. (Positive Number) ERROR_TEXT: FRM error message and number.

425 Structure of ON-ERROR Trigger
BEGIN --trap FRM errors IF ERROR_CODE = FRM_error_code1 THEN error handler; ELSIF ERROR_CODE = FRM_error_code2 THEN ELSE --trap ORA errors IF DBMS_ERROR_CODE = -ORA_error_code1 THEN error handler ELSIF DBMS_ERROR_CODE = -ORA_error_code2 THEN END IF END IF; END; Code to trap –FRM errors Code to trap –ORA errors

426 Form Validation Ensures that form data meets preset requirements so erroneous data is not sent to database Using validation properties or using validation triggers.

427 Form Validation Categories
Data Specifies data types, lengths, and maximum and minimum values Database Specifies which operations a user can perform on a text item List of Values Specifies whether a data value must be validated against the text item’s LOV (Validate From List text item property)

428 Validation Properties
Validation unit form property: specifies the largest data chunk that the user can enter before validation occurs Can be performed at the form, block, record, or item level Specified in the Validation Unit property on the form Property Palette By default, it is set to item level.

429 Cont. You should use the item level with the custom forms, and the record or block level with the data block forms. The validation properties that are checked always and before checking other properties and triggers are: format mask, required, datatype, range, and validate from list

430 Text Item Validation Properties
Data Type Minimum Value Maximum Value Validate From List Insert Allowed Query Allowed Required

431 Question Why do not we use validation properties instead of validation triggers?

432 We use validation triggers for more complex validations. (like what?)
Answer We use validation triggers for more complex validations. (like what?)

433 Validation Triggers When Validate Item
It should be Item level trigger. Executes when the item validation occurs depending on Validation Unit property. E.g. : IF NOT :student.s_class IN (‘FR’,’SO’) THEN Message(‘Legal Values are FR and SO); RAISE FORM_TRIGGER_FAILURE; END IF;

434 How To Disable Buttons SET_ITEM_PROPERTY E.g. :
SET_ITEM_PROPERTY(‘Control.Delete’ , ENABLED, PROPERTY_FALSE);

435 Data Blocks vs. Control Blocks
Easy to create and use Is associated with a single table, and reflects the table’s structure Control block Requires a lot of custom programming Can contain items from many different tables You can link data and control blocks to take advantages of the strengths of each

436 Linking Data Blocks and Control Blocks
Create the control block as the master block Create the data block as the detail block, but do not create a master-detail relationship Create a master-detail relationship manually in the WHERE Clause property of the detail block: data_block_field := control_block.text_item

437 Displaying and Refreshing the Data Block Values
Create a trigger to: Place the insertion point in the data block GO_BLOCK(‘block_name’); Flush the data block to make its data consistent with the master block and the database: EXECUTE_QUERY;

438 Converting a Data Block to a Control Block
Create a data block and layout that contains most of the required text items Convert the data block to a control block by changing the following block properties: Database Data Block = No Required = No

439 Creating a Form with Multiple Canvases
Users should be able to see all canvas text items without scrolling For complex applications with many text items, divide application into multiple canvases

440 Block Navigation Order
First block in Object Navigator Data Blocks list determines block items that first appear when form opens Users can use the Tab key to navigate among different block items Canvas that contains block items automatically appears

441 Block Navigation Order
Block order Canvas order doesn’t matter

442 Controlling Block Navigation
Block Navigation Style property Same Record: navigation cycles through items on same block Change Data Block: navigation moves to next data block in list

443 Canvas It is the surface that has the form items on it.
It has many types: Content (The default) Tab Stacked To display the canvas at runtime, use the canvas property ‘Window’.

444 Tab Canvases Multiple-page canvases that allow users to move among different canvas surfaces by clicking tabs

445 Tab Canvas Components Tab canvas Tab pages Tab labels
Collection of related tab pages Tab pages Surfaces that display form items Tab labels Identifier at top of tab page A tab canvas lies on top of a content canvas

446 Creating a Tab Canvas Use the Tab Canvas tool on the Layout Editor tool palette to draw a tab canvas on an existing content canvas By default, a new tab canvas has 2 tab pages Create new tab pages as needed Adjust tab page properties

447 Important Tab Page Properties
Name: how the page Is referenced in the form Label: Caption that appears on the associated tab

448 Adjusting the Tab Page Order
Tab page that appears first is tab page whose block items appear first in the Object Navigator Block order Tab page order doesn’t matter

449 Stacked Canvases Canvas that appears on an existing content canvas, and can be displayed or hidden as needed Allows user to configure canvas items

450 Stacked Canvas Example
Content canvas Stacked canvas

451 Creating a Stacked Canvas
Use the Stacked Canvas tool on the Layout Editor tool palette to draw a stacked canvas on an existing content canvas Create block items on the stacked canvas Create buttons and triggers to display and hide the stacked canvas

452 Displaying and Hiding a Stacked Canvas
Displaying a stacked canvas: GO_BLOCK(‘stacked_canvas_block’); SHOW_VIEW(‘stacked_canvas’); Hiding a stacked canvas: GO_BLOCK(‘content_canvas_block’); HIDE_VIEW(‘stacked_canvas’);

453 Chapter 7: Creating Database Reports
Guide to Oracle 10g

454 Lesson A Objectives After completing this lesson, you should be able to: Use the Reports Builder report styles Use the Report Wizard to create a report Configure the appearance of a report View a report in a Web browser Create a master-detail report Guide to Oracle 10g

455 Lesson A Objectives (continued)
Create a custom template Apply a custom template to a report Guide to Oracle 10g

456 Introduction to Reports Builder Database Reports
Allows application developers to create reports that display data from Oracle 10g database Developer10g Reports Builder allows developers to preview and distribute reports in variety of different formats including: Web pages Portable document format (.pdf) files Guide to Oracle 10g

457 Introduction to Reports Builder Database Reports (continued)
Layout styles: Tabular Form Mailing label Form letter Group left group above Matrix Matrix with group Guide to Oracle 10g

458 Using the Report Wizard to Create a Report
Steps: Specify data that report displays Select report style Configure report properties and layout Report Wizard pages: Welcome Report type Style Data source Guide to Oracle 10g

459 Using the Report Wizard to Create a Report (continued)
Report Wizard pages (continued): Data Fields Shows data fields that SQL query returns Totals Labels Template Finish Guide to Oracle 10g

460 Configuring the Report Appearance
Use Reports Builder environment to: Modify report appearance Customize report features Paper Design window Default editing environment Refine appearance of reports Shows how report will appear on paper Can preview as Web page Guide to Oracle 10g

461 Configuring the Report Appearance (continued)
Data Model button Modify report data Web Source button Displays underlying HTML code Defines how report will appear in Web browser Paper Layout button Opens report in Paper Layout view Guide to Oracle 10g

462 Configuring the Report Appearance (continued)
Paper Parameter Form button View parameter form Parameter form User selects input parameter values to customize form appearance and functionality at runtime Save report design specification using variety of formats Reports Builder design files Rdf extension Guide to Oracle 10g

463 Using the Report Wizard in Reentrant Mode
Modify SQL query To use ORDER BY clause Guide to Oracle 10g

464 The Reports Builder Object Navigator Window
View report components in hierarchical tree structure Access different components in Reports Builder environment Access components of individual report Reports Top-level node Guide to Oracle 10g

465 The Reports Builder Object Navigator Window (continued)
Other objects: Templates PL/SQL libraries Debug actions Stack Built-in packages Database objects Guide to Oracle 10g

466 Reports Builder Object Navigator
Guide to Oracle 10g

467 Modifying the Report Appearance in the Paper Design Window
Report title appears in report margin Area on page beyond where report data appears Adjust column’s width Select column Drag to make it wider or narrower Specify format masks for fields that display number and date data Property Inspector Guide to Oracle 10g

468 Modifying the Report Appearance in the Paper Design Window (continued)
Import graphic images into reports Same as importing graphic images into forms Guide to Oracle 10g

469 Closing and Reopening Reports
To close report: Click File on menu bar Click Close To open report: On Welcome to Reports Builder dialog Click Open an existing report option button Click OK Guide to Oracle 10g

470 Viewing the Report as a Web Page
Preview report as Web page Click Run Web Layout button Web page source code File with .htm extension Contains HTML commands and text to represent report content and formatting Guide to Oracle 10g

471 Viewing the Report as a Web Page (continued)
View formatting changes in Web page output Preview report using either: Paginated HTML Paginated HTMLCSS format Guide to Oracle 10g

472 Creating a Master-Detail Report
One record has many associated detail records Through foreign key relationship Use Report Wizard to specify report style and data values Report’s SQL query must retrieve all master and detail values Report Wizard displays groups page Guide to Oracle 10g

473 Specifying the Style and Data
Create new report in object navigator Select Reports node Click Create button Styles for creating master-detail reports Group left Group above Guide to Oracle 10g

474 Using the Groups Page to Specify Master-Detail Relationships
Data in master-detail report has multiple levels Each data level represents group Top-level (master) group is level 1 Specify report groups Move fields for each group from available fields list to group fields list Guide to Oracle 10g

475 Report Templates Many reports that have similar appearance
Useful to create custom template to specify report appearance Avoid performing same formatting tasks over and over again Guide to Oracle 10g

476 Creating a Custom Template
Custom template defines: Font sizes and styles for report’s Title Column headings Data values Text and background colors Boilerplate objects Store template definition in template definition file that has .tdf extension Guide to Oracle 10g

477 The Paper Layout Template Editor Window
Environment within Paper Layout window Used for editing templates Similar to forms builder layout editor Areas within painting region in report template Margin Body Guide to Oracle 10g

478 Paper Layout Template Editor
Guide to Oracle 10g

479 Editing Template Margins
Open margins for editing Click Margin button Guide to Oracle 10g

480 Editing the Template Body
Report body has two types of attributes: Default Override Frame Object that encloses similar objects within report Parent frame Frame that directly encloses object Guide to Oracle 10g

481 Applying Custom Templates to Reports
Modify existing report’s template by Opening Report Wizard in reentrant mode Changing template specification Guide to Oracle 10g

482 Applying Templates by Specifying the Template Filename
Select Template file specification option button on Report Wizard template page Enter full folder path and filename of template file Including drive letter Quick and easy way to apply custom templates Disadvantage Template file must be available at specified file location whenever report file opened Guide to Oracle 10g

483 Registering Custom Templates in Reports Builder
Appears in predefined templates list on template page Advantage Don’t have to specify path to template file File does not always have to be available Two-step process: Modify developer user preferences file Copy template file to Reports Builder templates folder Guide to Oracle 10g

484 Registering Custom Templates in Reports Builder (continued)
User preferences file Template description Template filename Template page displays thumbnail images of predefined templates Create thumbnail image of custom template Save screenshot as Bmp file Guide to Oracle 10g

485 Lesson A Summary Report Create report Paper design window
Summary view of database data that users can view on screen or print on paper Create report Specify data to appear in report Select report style Configure report properties and layout Paper design window The Reports Builder Object Navigator Guide to Oracle 10g

486 Lesson A Summary (continued)
Create master-detail report using Report Wizard Report template Defines report appearance Guide to Oracle 10g

487 Lesson B Objectives After completing this lesson, you should be able to: Describe the components of a report Modify report components Modify the format of master-detail reports Create parameters to allow the user to customize report data Guide to Oracle 10g

488 Report Components Data Model Paper Layout view Report frames
Specifies data that report displays Paper Layout view Displays report components as symbolic objects Report frames Group related report objects Guide to Oracle 10g

489 The Data Model Window Shows report’s SQL query and associated record groups Report record group Set of records represents data fields that query retrieves Simple tabular report has single record group Master-detail report has multiple record groups Components in report Data Model have properties Inspect using Property Inspector Guide to Oracle 10g

490 Report Record Group Column Types
Guide to Oracle 10g

491 The Data Model Window (continued)
Group filter Uses some criteria to limit number of records that report query retrieves To create: Assign value to filter type property Guide to Oracle 10g

492 Understanding Report Objects
Repeating rows Each row shows same data fields with different data values Report sections: Header Main Trailer Guide to Oracle 10g

493 Report Frames Frames Group frame
Containers for grouping related report objects Set specific properties for group of objects Rather than having to set property for each item Group frame Encloses repeating frame and optional header frame Guide to Oracle 10g

494 Report Frames (continued)
Repeating frame Encloses repeating data rows Has variable sizing Header frame Encloses all column headings for record group Move object outside enclosing frame Error message appears in Reports Builder Guide to Oracle 10g

495 Report Frames (continued)
Report Wizard derives frame names from names of associated record groups Select specific report frame in Paper Layout window Select item that in frame Select item’s parent frame by clicking Select Parent Frame button Change frame properties on frame Property Inspector Guide to Oracle 10g

496 Components of a Master-Detail Report
Multiple record groups Multiple group frames Guide to Oracle 10g

497 Master-Detail Data Model
More complex than Data Model for single-table report Contains multiple record groups Data Model groups report record groups according to master-detail relationships Each data link between two record groups represents master-detail relationship Guide to Oracle 10g

498 Master-Detail Data Model
Guide to Oracle 10g

499 Master-Detail Report Frames
Each record group has associated group frame Group frames for more detailed record groups nested inside group frames for less detailed record groups Frame relationships can be hard to see Many frames appear directly on top of each other Open frame Property Inspector immediately after selecting frame To check frame name Guide to Oracle 10g

500 Modifying Master-Detail Report Properties
Page break between sets of repeating records Open Property Inspector for repeating frame Change Maximum Records per Page property to 1 Confine mode Determines objects can be moved outside enclosing frames Always safest to leave enabled Guide to Oracle 10g

501 Modifying Master-Detail Report Properties (continued)
Flex mode Enclosing frame automatically becomes larger When enclosed object moved beyond enclosing frame’s boundary Overrides confine mode When moving report layout field Automatically resizes all surrounding frames Works well when to make a frame longer But not wider Guide to Oracle 10g

502 Modifying Master-Detail Report Properties (continued)
Elasticity Determines whether field’s size fixed Or whether field can expand or contract automatically Depending on height and width of retrieved data value Guide to Oracle 10g

503 Report Field Elasticity Indicators
Guide to Oracle 10g

504 Report Parameters Specifies how report appears
Specifies report’s behavior when it runs Types: System User Guide to Oracle 10g

505 System Parameters Guide to Oracle 10g

506 User Parameters User selects user parameter value from parameter list
Shows possible values Modify report to include user parameter Create user parameter Create parameter list Modify report query to use parameter as search condition Guide to Oracle 10g

507 User Parameters (continued)
Parameter object name Parameter data type Configure list of values property in user parameter Property Inspector Syntax: :parameter_name Parameter form Displays title and hint line list of one or more parameters with associated prompts. Guide to Oracle 10g

508 Customizing the Report Parameter Form
Change text that appears in title and hint line Reposition form items Add additional text and graphics Use parameter form builder utility Also lists all of system parameters User can modify at runtime Guide to Oracle 10g

509 Lesson B Summary Data Model window shows: Create group filter
Report query Record groups it generates Data links between query and record group Create group filter To limit number of records report query retrieves Paper Layout window displays layout field for each Data Model column Guide to Oracle 10g

510 Lesson B Summary (continued)
Frames Containers for grouping report record group data items and column headings Report parameters System User Guide to Oracle 10g

511 Lesson C Objectives After completing this lesson, you should be able to: Display image data in a report Manually create queries and data links Create summary columns Create formula columns Create reports that display formatted data in a Web browser window Guide to Oracle 10g

512 Displaying Image Data in Reports
Store image data with LOB data type Create report based on table that has field with BLOB data type And contains image data Guide to Oracle 10g

513 Creating and Configuring the Report Image Layout Fields
Use Report Wizard to create report All data fields automatically appear as text If column contains multimedia data Data appears as text characters “MM” Modify field by: Opening Property Inspector Changing File Format property to image Guide to Oracle 10g

514 Creating Report Queries and Data Links Manually
Create query manually Retrieve master records Create query manually that retrieves detail records Create data link between two queries, Create layout fields to display query data Guide to Oracle 10g

515 Creating Queries and Data Links Manually (continued)
Create query manually (continued) Open Data Model window Select SQL query tool Click in painting region Type SQL query Manually create data links to represent master-detail relationships between queries Master = parent Detail = child Guide to Oracle 10g

516 Creating Queries and Data Links Manually (continued)
Types of data links Query to Query Group to Group Column to Column Guide to Oracle 10g

517 Manually Linked Queries
Guide to Oracle 10g

518 Creating the Label, Repeating Frame, and Layout Fields
Guide to Oracle 10g

519 Creating Reports that Display Calculated Values
Formula columns Display values that PL/SQL functions calculate using report data field values as input parameters Summary columns Perform summary functions Guide to Oracle 10g

520 Creating Formula Columns
Function Self-contained program block Returns single value User-defined functions Use PL/SQL commands to calculate return value Formula column Displays value that user-defined function returns Guide to Oracle 10g

521 Creating Formula Columns (continued)
Create and display formula column Create formula column in report Data Model Write user-defined function Create layout field in report Guide to Oracle 10g

522 Creating a Formula Column in the Report Data Model
Click Formula Column tool Be careful to place formula column in same record group as columns that formula function uses in calculations Guide to Oracle 10g

523 Creating the Formula Column Function
Guide to Oracle 10g

524 Creating a Layout Field to Display the Formula Column
Display formula column on report Open Paper Layout window Use Field tool to create new report layout field Place layout field in same repeating frame as source values for formula Set new field’s Source property to name of formula column Guide to Oracle 10g

525 Creating Summary Columns
Returns summary value of series of data fields in repeating frame Create Using totals page in Report Wizard Manually Guide to Oracle 10g

526 Creating a Summary Column Using the Report Wizard
Select field to be summarized and summary function on Report Wizard totals page Wizard automatically: Modifies report Data Model Creates fields to display summary column on report layout Guide to Oracle 10g

527 Creating a Summary Column Manually
Using Report Wizard Eliminates all custom formatting Deletes custom objects Create summary column manually Control summary column placement and frequency Retain other custom objects Guide to Oracle 10g

528 Creating a Summary Column Manually (continued)
Tasks: Create summary column in report Data Model Using summary column tool Modify summary column properties Create layout field Place layout field in repeating frame that corresponds to record group that contains summary column Guide to Oracle 10g

529 Displaying Formatted Reports as Web Pages
View report in Paginated HTML or Paginated HTMLCSS format Reports Builder translates report into static Web page Content fixed at time developer generates page Not updated with database changes Guide to Oracle 10g

530 Using the Oracle 10g Application Server to Generate Reports Dynamically
Oracle 10g Application Server (OAS) Web server Oracle corporation uses to deliver Web-based Oracle 10g database applications to users Report Server process Queries database when user requests report Generates dynamic Web page Displays current database data Guide to Oracle 10g

531 Creating a Dynamic Web Page that Displays Database Data
Guide to Oracle 10g

532 Creating Reports that Appear as Dynamic Web Pages
Create report using techniques learned in this chapter Save report in either: Report definition file (RDF) Java server page ( JSP) format Guide to Oracle 10g

533 Creating Reports that Appear as Dynamic Web Pages (continued)
Techniques for modifying appearance of Web reports: Use Web source window to modify default formatting Open existing HTML file in Reports Builder that contains formatting for report Use Reports Builder to add commands to retrieve and display report data Guide to Oracle 10g

534 Overview of HTML Documents
Text file with .htm or .html extension Contains formatting symbols called tags Define how Web page appears in Web browser Enclose in angle brackets Opening tag Closing tag Elements Represent content that appears on Web page such as text and graphic images Guide to Oracle 10g

535 Basic HTML Document Structure
Guide to Oracle 10g

536 Viewing the Report Web Source File
Web source file contains HTML tags that define report appearance Program commands that create dynamic report elements Web report embeds program commands using tags Similar to html tags Prefaced by rw: Same for reports in either format Guide to Oracle 10g

537 Viewing the Report Web Source File (continued)
Java commands appear enclosed in the <% and %> command delimiters Data area Contains commands that dynamically retrieve and display report data Follow html comment with text <!--Data Area Generated by Reports Developer --> Guide to Oracle 10g

538 Modifying the Default Appearance of a Web Report
Techniques for modifying appearance of Web reports: Use Web Source window to modify default formatting Open existing HTML file in Reports Builder that contains formatting for report Use Reports Builder to add commands to retrieve and display report data Guide to Oracle 10g

539 Modifying the Default Appearance of a Web Report (continued)
Report Block Wizard pages: Style page Groups page Fields page Labels page Template page Guide to Oracle 10g

540 Lesson C Summary Create report displays LOB data field
Manually create queries and data links in Data Model view Create layout fields to display values that queries retrieve Create formula and summary columns Oracle 10g Application Server (OAS) Display dynamic reports Guide to Oracle 10g

541 Summary Report Report template Data Model window Paper Layout window
Summary view of database data that users can view on screen or print on paper Report template Data Model window Paper Layout window Frames Oracle 10g Application Server (OAS) Guide to Oracle 10g

542 Chapter 9: Advanced SQL and PL/SQL
Guide to Oracle 10g

543 Lesson A Objectives After completing this lesson, you should be able to: Work with PL/SQL stored units Guide to Oracle 10g

544 PL/SQL Stored Program Units
A program unit is a self-contained group of program statements that can be used within a large program PL/SQL part written in the form builder that may be called by a form trigger is an example of a unit. The unit you created and executed so far in a form builder or SQL*Plus are anonymous PL/SQL programs which are Programs submitted to the interpreter and run Do not interact with other program units They only exist within forms Guide to Oracle 10g

545 PL/SQL Stored Program Units
Stored PL/SQL program units are: program units that other PL/SQL program can reference, and that other database users can use and execute. What do stored units can do? It can receive input values from other program units It can pass output values to other program units Stored unit can be linked to database application components created in Form builder to enhance their functionality. Guide to Oracle 10g

546 PL/SQL Stored Program Units
It can be either Server-side program units: stored as database object and execute on the sever (can be used by all users) Client-side program units: stored in the file system of a client workstation and execute on the client workstation Guide to Oracle 10g

547 Creating Stored program Units
Stored program units can be either: Procedures: Can receive multiple input parameters and return multiple output values (or no output values) Can perform an action such insert, update or delete record Functions: Can receive multiple input parameters and always returns a single output value Guide to Oracle 10g

548 Creating Procedures IS [local variable declaration_section] BEGIN
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter mod datatype [,parameter]) ] IS [local variable declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name]; Header Section body Exception section Guide to Oracle 10g

549 Creating Procedures Guide to Oracle 10g

550 Creating Procedures The header section defines:
The procedure name (name should be unique ) The parameters that the procedure receives or delivers (IN, OUT, IN OUT) IS keyword: follows the parameters list The local procedure variables Create or replace: instructs the DBMS to create the procedure if it does it exists, otherwise; it replaces the existing one OR REPLACE clause is optional. But if omitted and a procedure exists with the same name, an error occurs Guide to Oracle 10g

551 Creating Procedures (parameters list)
Parameter name, mod and data type are enclosed in parentheses, each is separated by a comma. Parameter mod: describes how the procedure change the value. It can be: IN: passed parameter is a Read only value. Cannot be changed by the procedure OUT: write-only value. Always comes on the left side of an assignment statement IN OUT: its value can be changed Guide to Oracle 10g

552 Creating Procedures (parameters list)
The data type cannot specify a length, precision, or scale value for a numerical data type, or maximum length of a character data type. Oracle Database derives the length, precision, or scale of the return value from the environment from which the function is called. When the procedure or function is created and debugged, it ca be called from any application. Guide to Oracle 10g

553 Creating Procedures (Example)
UPDATE_ENROLLMENT_GRADE: a procedure that updates a student’s grade for a course. It accepts 3 input parameters (student ID, Course section ID and grade) Upon successful, the stored procedure exists as an object in your schema. Guide to Oracle 10g

554 Creating Procedures (Example)
The (%ROWTYPE) reference data type creates composite variables that reference the entire data record. Faculty_row FACULTY%ROWTYPE; The variable faculty_row references all of the columns in the FACULTY table, and each column has the same data type as its associated DB column. NO Data Size Guide to Oracle 10g

555 Debugging program units (SQL*Plus)
Interpreter displays only a warning message. It does not contain a compiler error message nor a line location. Instead, it writes all compiler errors to a system table accessed using USER_ERRORS data dictionary view. It displays a summary listing of compile errors generated by the last program unit that was compiled. Use the SHOW ERRORS command: See Figure 9-12. Guide to Oracle 10g

556 Calling a Stored Procedure
Execute directly from SQL*Plus command line Create separate PL/SQL program that contains Command to call stored procedure Passes parameter values to procedure Calling stored procedure from SQL*Plus command line: EXECUTE procedure_name (parameter1_value, parameter2_value, ...); Execute update_enrollment_grade(‘MA100’, 12, ‘B’); Single quote for character is important. Variables passed for each parameter must be in same order as parameters appear in parameter declarations list Guide to Oracle 10g

557 Calling a Stored Procedure
Calling stored procedure from separate PL/SQL program Similar to calling stored procedure from SQL*Plus command line Omit EXECUTE command update_enrollment_grade(‘MA100’, 12, ‘B’); Guide to Oracle 10g

558 Creating Functions A function is similar to a procedure, except that it returns a single value. Guide to Oracle 10g

559 Creating Functions The function name (name should be unique ) The syntax of the parameter list is identical to that of the procedure. After the parameters list, RETURN sentence determines the data type of the return value of the function. (remember that procedure does not return a value, so it contains NO Return statement) After IS, the return_value_variable declares the variable that represents the function return value. Guide to Oracle 10g

560 Creating Functions Guide to Oracle 10g

561 Calling a Functions Calling a function requires assignment the command to a previously declared variable in the calling program, since the function returns a single data value. variable_name := function_name(parameter1, parameter2, ...); Variables passed for parameter values Must be in same order as parameters appear in function declaration Guide to Oracle 10g

562 Pay attention to to_date function.
Calling a Functions Pay attention to to_date function. Guide to Oracle 10g

563 End of Chapter 9: Advanced SQL and PL/SQL
Guide to Oracle 10g


Download ppt "Client/Server Databases and the Oracle 10g Relational Database"

Similar presentations


Ads by Google