Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 1 Introduction to PL/SQL Oracle10g Developer:

Similar presentations


Presentation on theme: "Chapter 1 Introduction to PL/SQL Oracle10g Developer:"— Presentation transcript:

1 Chapter 1 Introduction to PL/SQL Oracle10g Developer:
PL/SQL Programming Chapter 1 Introduction to PL/SQL

2 Chapter Objectives After completing this lesson, you should be able to understand: PL/SQL and application programming Application models How documentation can be used SQL and PL/SQL tools The databases used in this book SQL SELECT statement syntax Oracle10g Developer: PL/SQL Programming

3 Procedural Languages Programming languages allow actions of the end user to be converted to computer instructions Procedural languages allow the inclusion of logic processes PL/SQL is a procedural language, SQL is not a procedural language Oracle10g Developer: PL/SQL Programming

4 Application Programming
Example application screen Oracle10g Developer: PL/SQL Programming

5 Brewbean’s Application
Processing needed to support the shopping cart check out button Verify quantities are > 0 Calculate shipping cost Calculate taxes Check/update product inventory Check shopper profile for credit card information Oracle10g Developer: PL/SQL Programming

6 The PL/SQL Language Proprietary Oracle language
Tightly integrated with SQL Can increase performance by grouping statements into blocks of code Portable to any Oracle platform Used within many Oracle tools Stored program units can increase security Oracle10g Developer: PL/SQL Programming

7 Application Models Three main components
User interface or screens Program logic (brains behind the screens) Database Most models are based on a two- or three-tier structure Oracle10g Developer: PL/SQL Programming

8 Two-tier Model Commonly referred to as client/server
Parts of the processing occur both on the user’s computer and the database server Named or stored program units are blocks of PL/SQL code saved in the Oracle database to provide server-side processing Oracle10g Developer: PL/SQL Programming

9 Two-tier Diagram Oracle10g Developer: PL/SQL Programming

10 Three-tier Model Thin client with no code loaded on the user machine (browser access) Middle tier is the application server – Forms server for Oracle Last tier is the database server Processing load is on the middle and last tier Maintenance is simplified Oracle10g Developer: PL/SQL Programming

11 Three-tier Diagram Oracle10g Developer: PL/SQL Programming

12 Oracle Documentation Oracle Technology Network (OTN): otn.oracle.com
Doc directory on CDs distributed by Oracle Oracle10g Developer: PL/SQL Programming

13 Software Used SQL*Plus – Oracle10g
Other software introduced in appendices Oracle SQL Developer TOAD Oracle10g Developer: PL/SQL Programming

14 SQL*Plus Client Interface
Oracle10g Developer: PL/SQL Programming

15 SQL*Plus Internet Interface
Named iSQL*Plus Oracle10g Developer: PL/SQL Programming

16 Third-party Tools TOAD Rapid SQL PL/SQL Developer SQL-Programmer
PLEdit FROG Oracle10g Developer: PL/SQL Programming

17 The Brewbean’s Company
Retails coffee and brewing equipment via the Internet, phone, and stores Used in chapter explanations, examples, and exercises Databases create script provided for each chapter Oracle10g Developer: PL/SQL Programming

18 ERD for Brewbean’s DB Oracle10g Developer: PL/SQL Programming

19 More Movies ERD Movie rental company used in an ongoing case study
Oracle10g Developer: PL/SQL Programming

20 SQL Query Syntax SELECT <columns> FROM <tables, views>
WHERE <conditions> GROUP BY <columns> HAVING <aggregation conditions> ORDER BY <columns>; Oracle10g Developer: PL/SQL Programming

21 Traditional Join Oracle10g Developer: PL/SQL Programming

22 ANSI Join Oracle10g Developer: PL/SQL Programming

23 Using Aggregate and WHERE
Oracle10g Developer: PL/SQL Programming

24 Creating Tables Oracle10g Developer: PL/SQL Programming

25 DML Statements Oracle10g Developer: PL/SQL Programming

26 Chapter 2 Basic PL/SQL Block Structures Oracle10g Developer:
PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures

27 Chapter Objectives After completing this lesson, you should be able to understand: Programming fundamentals The PL/SQL block How to define and declare variables How to initialize variables The NOT NULL and CONSTANT variable options Oracle10g Developer: PL/SQL Programming

28 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): How to perform calculations with variables The use of SQL single-row functions in PL/SQL statements Decision structures: IF-THEN and CASE Looping actions SQL*Plus bind variables Oracle10g Developer: PL/SQL Programming

29 Program Logic Flow Identify sequence of actions needed prior to coding
Use a flowchart to visually represent the sequence of actions Oracle10g Developer: PL/SQL Programming

30 Flowcharting - Search for Coffee Products
Oracle10g Developer: PL/SQL Programming

31 Decision Structures Oracle10g Developer: PL/SQL Programming

32 Looping Structures Oracle10g Developer: PL/SQL Programming

33 PL/SQL Block Questions
What is a block? What are the different segments of a block? How does data get into a block? How are different data types handled? Oracle10g Developer: PL/SQL Programming

34 Brewbean’s Challenge Oracle10g Developer: PL/SQL Programming

35 PL/SQL Block Structure
DECLARE – create variables, cursors, and types BEGIN – SQL, logic, loops, assignment statements EXCEPTION – error handling END – close the block Oracle10g Developer: PL/SQL Programming

36 Variable Names Begin with alpha character Up to 30 characters
Can contain upper and lowercase letters, numbers, _ , $ , # Oracle10g Developer: PL/SQL Programming

37 Scalar Variable Data Types
Character – CHAR(n) VARCHAR2(n) Numeric – NUMBER(p,s) Date – DATE Boolean – BOOLEAN Note: Only holds a single value Oracle10g Developer: PL/SQL Programming

38 Example Scalar Declarations
DECLARE lv_ord_date DATE; lv_last_txt VARCHAR2(25); lv_qty_num NUMBER(2); lv_shipflag_bln BOOLEAN; BEGIN ---- PL/SQL executable statements ---- END; Note: Minimum requirements are variable name and data type Oracle10g Developer: PL/SQL Programming

39 Test Variables Oracle10g Developer: PL/SQL Programming

40 Variable Initialization
Set a variable value when the variable is created DECLARE lv_ord_date DATE := SYSDATE; lv_last_txt VARCHAR2(25) := 'Unknown'; lv_qty_num NUMBER(2) := 0; lv_shipflag_bln BOOLEAN := 'FALSE'; BEGIN ---- PL/SQL executable statements ---- END; Oracle10g Developer: PL/SQL Programming

41 Test Variable Initialization
Oracle10g Developer: PL/SQL Programming

42 Variable Declaration Options
NOT NULL – the variable must always contain a value CONSTANT – the variable value can not be changed in the block DECLARE lv_shipcntry_txt VARCHAR2(15) NOT NULL := 'US'; lv_taxrate_num CONSTANT NUMBER(2,2) := .06; BEGIN ---- PL/SQL executable statements ---- END; Oracle10g Developer: PL/SQL Programming

43 Calculations with Scalar Variables
multiplication DECLARE lv_taxrate_num CONSTANT NUMBER(2,2) := .06; lv_total_num NUMBER(6,2) := 50; lv_taxamt_num NUMBER(4,2); BEGIN lv_taxamt_num := lv_total_num * lv_taxrate_num; DBMS_OUTPUT.PUT_LINE(lv_taxamt_num); END; / Oracle10g Developer: PL/SQL Programming

44 Using SQL Functions SQL functions such as MONTHS_BETWEEN can be used
within PL/SQL statements Oracle10g Developer: PL/SQL Programming

45 Decision Structures (continued)
Control which statements in a PL/SQL block will execute Enables conditions to be tested to determine the flow of statement execution Most programming languages provide IF and CASE statements to enable conditional processing Oracle10g Developer: PL/SQL Programming

46 Decision Structures (continued)
IF Statements Simple IF IF/THEN/ELSE IF/THEN/ELSIF/ELSE CASE Statements Basic CASE statement Searched CASE statement CASE expression Oracle10g Developer: PL/SQL Programming

47 Simple IF Statement Oracle10g Developer: PL/SQL Programming

48 IF/THEN/ELSE Oracle10g Developer: PL/SQL Programming

49 IF/THEN/ELSIF/ELSE Oracle10g Developer: PL/SQL Programming

50 Logical Operators within IF
Logical operators (AND, OR) enable multiple conditions to be checked IF lv_state_txt = 'VA' OR lv_state_txt = 'PA' THEN lv_tax_num := lv_sub_num * .06; ELSE lv_tax_num := lv_sub_num * .04; END IF; Oracle10g Developer: PL/SQL Programming

51 Basic CASE Statement Oracle10g Developer: PL/SQL Programming

52 Searched CASE Oracle10g Developer: PL/SQL Programming

53 CASE Expression Oracle10g Developer: PL/SQL Programming

54 Looping Enables a statement or set of statements to be executed more than once A loop must provide instructions of when to end the looping, or an ‘infinite’ loop will be produced Oracle10g Developer: PL/SQL Programming

55 Basic LOOP Oracle10g Developer: PL/SQL Programming

56 WHILE Loop Oracle10g Developer: PL/SQL Programming

57 FOR Loop Oracle10g Developer: PL/SQL Programming

58 Host/Bind Variables Declare
Using application environment variables to send variables into and out of a PL/SQL block SQL*Plus is an application environment BEGIN :g_state_txt := 'VA'; END; / Oracle10g Developer: PL/SQL Programming

59 Using Host/Bind Variables
DECLARE lv_tax_num NUMBER(4,2); lv_sub_num NUMBER(6,2) := 100; BEGIN IF :g_state_txt = 'VA' THEN lv_tax_num := lv_sub_num * .06; ELSIF :g_state_txt = 'CA' THEN lv_tax_num := lv_sub_num * .08; ELSE lv_tax_num := lv_sub_num * .04; END IF; DBMS_OUTPUT.PUT_LINE(lv_tax_num); END; / Oracle10g Developer: PL/SQL Programming

60 Summary A flowchart assists in laying out processing logic
A PL/SQL block contains a DECLARE, BEGIN, EXCEPTION, and END sections Variables to hold values are declared Scalar variables hold a single data value Scalar variables can hold string values, numbers, dates, and Boolean values DBMS_OUTPUT.PUT_LINE is used to display values Oracle10g Developer: PL/SQL Programming

61 Summary (continued) IF statement structure is IF/THEN/ELSIF/ELSE
CASE statements provide decision processing similar to IF statements Looping structures include: basic, WHILE, and FOR Host or bind variables can be used to interact with the application environment Oracle10g Developer: PL/SQL Programming

62 Chapter 3 Handling Data in PL/SQL Blocks Oracle10g Developer:
PL/SQL Programming Chapter 3 Handling Data in PL/SQL Blocks

63 Chapter Objectives After completing this lesson, you should be able to understand: SQL queries within PL/SQL Host or bind variables The %TYPE attribute Expanding block processing to include queries and control structures Oracle10g Developer: PL/SQL Programming

64 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Embedding DML statements within PL/SQL Composite data types Creating collections Understanding the GOTO statement Oracle10g Developer: PL/SQL Programming

65 Brewbean’s Challenge Consider actions needed upon check out
Oracle10g Developer: PL/SQL Programming

66 Include SQL within a Block
Data query needs to identify if the customer has a saved basket Oracle10g Developer: PL/SQL Programming

67 Include SQL within a Block (continued)
SQL statements can be embedded into the executable area of a PL/SQL block SELECT statements are embedded to query needed data An INTO clause is added to a SELECT statement to move data retrieved into variables Oracle10g Developer: PL/SQL Programming

68 Include SQL within a Block (continued)
Query – add INTO clause Assignment Statement Oracle10g Developer: PL/SQL Programming

69 Executing a Block with Errors
Common Errors Use = rather than := Not declaring a variable Misspelling a variable name Not ending a statement with ; No data returned from a SELECT statement Oracle10g Developer: PL/SQL Programming

70 Executing a Block with Errors (continued)
Not closing a statement with ; Oracle10g Developer: PL/SQL Programming

71 Host or Bind Variables Reference host variables with a preceding colon in PL/SQL BEGIN :g_shopper := 25; END; / WHERE idShopper = :g_shopper AND orderplaced = 0; Create host variable Reference host variable Oracle10g Developer: PL/SQL Programming

72 %TYPE Attribute Use in variable declaration to provide data type based on a table column Ideal for declaring variables that will hold data from the database Minimizes maintenance by avoiding program changes to reflect database column changes Called an anchored data type lv_basket_num bb_basket.idBasket%TYPE; Oracle10g Developer: PL/SQL Programming

73 Data Retrieval with Decision Structures
Oracle10g Developer: PL/SQL Programming

74 IF Statement Example Oracle10g Developer: PL/SQL Programming

75 Including DML DML statements can be embedded into PL/SQL blocks to accomplish data changes DML includes INSERT, UPDATE, and DELETE statements Oracle10g Developer: PL/SQL Programming

76 Including DML (continued)
Add a new shopper - INSERT Oracle10g Developer: PL/SQL Programming

77 Composite Data Types Stores multiple values of different data types as one unit Record – can hold one row of data Table of records – can hold multiple rows of data Oracle10g Developer: PL/SQL Programming

78 Record Data Type DECLARE TYPE type_basket IS RECORD (
basket bb_basket.idBasket%TYPE, created bb_basket.dtcreated%TYPE, qty bb_basket.quantity%TYPE, sub bb_basket.subtotal%TYPE); rec_basket type_basket; lv_days_num NUMBER(3); lv_shopper_num NUMBER(3) := 25; BEGIN SELECT idBasket, dtcreated, quantity, subtotal INTO rec_basket FROM bb_basket WHERE idShopper = lv_shopper_num AND orderplaced = 0; lv_days_num := SYSDATE - rec_basket.created; END; Oracle10g Developer: PL/SQL Programming

79 %ROWTYPE Attribute Create record structure based on table structure
DECLARE rec_shopper bb_shopper%ROWTYPE; BEGIN SELECT * INTO rec_shopper FROM bb_shopper WHERE idshopper = :g_shopper; DBMS_OUTPUT.PUT_LINE(rec_shopper.lastname); DBMS_OUTPUT.PUT_LINE(rec_shopper.address); DBMS_OUTPUT.PUT_LINE(rec_shopper. ); END; Oracle10g Developer: PL/SQL Programming

80 Table of Records Oracle10g Developer: PL/SQL Programming

81 Collections Store multiple values of the same data type
Similar to arrays in other languages Index-by Tables – handle many rows of one field One-dimensional Can only have one column Unconstrained Rows added dynamically as needed Sparse A row only exists when a value is assigned; rows do not have to be assigned sequentially Homogeneous All elements have same data type Indexed Integer index serves as primary key of the table Oracle10g Developer: PL/SQL Programming

82 Index-by Table Attributes
Attribute Name Value Data type Description COUNT NUMBER Number of rows in the table DELETE None Removes a row from the table EXISTS BOOLEAN TRUE if specified row does exist FIRST BINARY_INTEGER Index for the first row in the table LAST Index for the last row in the table NEXT Index for the next row in the table after the row specified PRIOR Index for the row in the table before the row specified Oracle10g Developer: PL/SQL Programming

83 Index-by Table Example
Host variables declaration and initialization Oracle10g Developer: PL/SQL Programming

84 Index-by Table Example
Index-by table data type declaration Index-by table variable declaration Put host variable values into the table variable A FOR loop adds all the sample measurements that have been entered into the table variable lv_avg_num calculates the Average measurement Oracle10g Developer: PL/SQL Programming

85 GOTO Statement Jumping control that instructs the program to move to another area of code to continue processing Most developers discourage the use of GOTO as it complicates the flow of execution Oracle10g Developer: PL/SQL Programming

86 Summary SQL queries and DML statements can be embedded into a block
An INTO clause must be added to a SELECT The %TYPE attribute is used to use a column data type Composite data types can hold multiple values in a single variable Oracle10g Developer: PL/SQL Programming

87 Summary (continued) A record can hold a row of data
A table of records can hold multiple rows of data The %ROWTYPE attribute can be used to declare a data type based on a table’s structure An index-by table is a collection similar to arrays The GOTO statement enables execution to jump to specific portions of code Oracle10g Developer: PL/SQL Programming

88 Chapter 4 Cursors and Exception Handling Oracle10g Developer:
PL/SQL Programming Chapter 4 Cursors and Exception Handling

89 Chapter Objectives After completing this lesson, you should be able to understand: Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling issues, such as RAISE_APPLICATION_ERROR and propagation Documenting code with comments Oracle10g Developer: PL/SQL Programming

90 Brewbean’s Challenge Processing multiple data rows
Oracle10g Developer: PL/SQL Programming

91 Cursors Work area in which SQL statement is processed
Implicit cursor – declared automatically for DML and SELECT statements Explicit cursor – declared and managed programmatically to handle a set of rows returned by a SELECT statement Cursor variable – reference or pointer to a work area or cursor Oracle10g Developer: PL/SQL Programming

92 Cursor Attributes Attribute Name Data type Description %ROWCOUNT
Number Number of rows affected by the SQL statement %FOUND Boolean TRUE if at least one row is affected by the SQL statement, otherwise FALSE %NOTFOUND TRUE if no rows are affected by the SQL statement, otherwise FALSE Oracle10g Developer: PL/SQL Programming

93 Implicit Cursor Oracle10g Developer: PL/SQL Programming

94 Explicit Cursor Step Step Activity Activity Description 1 DECLARE
Creates a named cursor identified by a SELECT statement. The SELECT statement does not include an INTO clause. Values in the cursor are moved to PL/SQL variables with the FETCH step. 2 OPEN Processes the query and creates the active set of rows available in the cursor. 3 FETCH Retrieves a row from the cursor into block variables. Each consecutive FETCH issued will retrieve the next row in the cursor until all rows have been retrieved. 4 CLOSE Clears the active set of rows and frees the memory area used for the cursor. Oracle10g Developer: PL/SQL Programming

95 Explicit Cursor Example
Declare cursor Declare record type and variable Open cursor Fetch a row from the cursor Check if row returned from fetch Close cursor Calculate tax amount Oracle10g Developer: PL/SQL Programming

96 Cursor FOR Loop Handles tasks automatically for processing each row returned by a cursor (record declaration, fetch, ending loop) Use FOR UPDATE and WHERE CURRENT OF clauses for record locking Oracle10g Developer: PL/SQL Programming

97 Cursor FOR Loop Example
DECLARE CURSOR cur_prod IS SELECT type, price FROM bb_product WHERE active = 1 FOR UPDATE NOWAIT; lv_sale bb_product.saleprice%TYPE; BEGIN FOR rec_prod IN cur_prod LOOP IF rec_prod.type = 'C' THEN lv_sale := rec_prod.price * .9; END IF; IF rec_prod.type = 'E' THEN lv_sale := rec_prod.price * .95; UPDATE bb_product SET saleprice = lv_sale WHERE CURRENT OF cur_prod; END LOOP; COMMIT; END; Oracle10g Developer: PL/SQL Programming

98 Cursor Variable More efficiently handles data returned by query by returning a pointer to the work area rather than the actual result set The same cursor variable can be used for different query statements Oracle10g Developer: PL/SQL Programming

99 Cursor Variable Example
DECLARE TYPE type_curvar IS REF CURSOR; cv_prod type_curvar; rec_coff bb_coffee%ROWTYPE; rec_equip bb_equip%ROWTYPE; BEGIN IF :g_choice = 1 THEN OPEN cv_prod FOR SELECT * FROM bb_coffee; FETCH cv_prod INTO rec_coff; . . . END IF; IF :g_choice = 2 THEN OPEN cv_prod FOR SELECT * FROM bb_equip; FETCH cv_prod INTO rec_equip; END; Oracle10g Developer: PL/SQL Programming

100 Exception Handlers Used to capture error conditions and handle the processing to allow the application to continue Placed in the EXCEPTION section of a PL/SQL block Two types of errors Oracle errors (Predefined and Non-Predefined) User-defined errors RAISE_APPLICATION_ERROR Oracle10g Developer: PL/SQL Programming

101 Predefined Oracle Errors
Exception Name Description NO_DATA_FOUND A SELECT statement in a PL/SQL block retrieves no rows or a nonexistent row of an index-by table is referenced TOO_MANY_ROWS A SELECT statement in a PL/SQL block retrieves more than one row CASE_NOT_FOUND No WHEN clause in the CASE statement is processed ZERO_DIVIDE Attempted division by zero DUP_VAL_ON_INDEX Attempted violation of a unique or primary key column constraint Oracle10g Developer: PL/SQL Programming

102 Predefined Error Example
Oracle10g Developer: PL/SQL Programming

103 Add Exception Handler Oracle10g Developer: PL/SQL Programming

104 Non-Predefined Error Identify possible errors for statements in a block Oracle10g Developer: PL/SQL Programming

105 Non-Predefined Handler Added
Declare an exception Associate an Oracle error number to the exception name Foreign key error occurs if item lines are still in the bb_basketitem table Exception handler executes if Foreign key error –2292 is raised by the DELETE Oracle10g Developer: PL/SQL Programming

106 User-Defined Exception
No system error is raised Raise errors to enforce business rules Once error is raised, the remaining statements in the executable sections are not executed Processing moves to the exception area of the block Oracle10g Developer: PL/SQL Programming

107 User-Defined Exception (continued)
Declare an exception If no rows updated, raise the exception Exception handler Oracle10g Developer: PL/SQL Programming

108 Additional Exception Concepts
WHEN OTHERS – traps all errors not specifically addressed by an exception handler and used for handling unanticipated errors SQLCODE and SQLERRM – functions used to identify the error code and message, especially in application, testing to identify unanticipated errors Oracle10g Developer: PL/SQL Programming

109 SQLCODE and SQLERRM Log error information to a database table using these functions Oracle10g Developer: PL/SQL Programming

110 RAISE_APPLICATION_ERROR
Allows developers to associate their own error number and message to an error Can only be used with stored programs, which is covered in Chapter 4 Oracle10g Developer: PL/SQL Programming

111 Exception Propagation
When an error occurs in a block, processing immediately moves to the EXCEPTION section of the block If the block is nested and no handlers address the error, the processing will then move to the EXCEPTION section of the enclosing block Oracle10g Developer: PL/SQL Programming

112 Commenting Code Add comments within code to identify code purpose and processing steps Use /* */ to enclose a multiline comment Use -- to add a single or partial line comment Oracle10g Developer: PL/SQL Programming

113 Comment Examples DECLARE
ex_prod_update EXCEPTION; --For UPDATE of no rows exception BEGIN /* This block is used to update product descriptions Constructed to support the Prod_desc.frm app screen Exception raised if no rows updated */ UPDATE bb_product SET description = 'Mill grinder with 5 grind settings!' WHERE idProduct = 30; --Check if any rows updated IF SQL%NOTFOUND THEN RAISE ex_prod_update; END IF; EXCEPTION WHEN ex_prod_update THEN DBMS_OUTPUT.PUT_LINE('Invalid product id entered'); END; Oracle10g Developer: PL/SQL Programming

114 Summary Implicit cursors are automatically created for SQL statements
Explicit cursors are declared Cursors allow the processing of a group of rows CURSOR FOR Loops simplify cursor coding Parameters make cursors more dynamic A REF CURSOR acts like a pointer Oracle10g Developer: PL/SQL Programming

115 Summary (continued) Add error handlers in the EXCEPTION area to manage Oracle and user-defined errors Use comments in code for documentation Oracle10g Developer: PL/SQL Programming

116 Oracle10g Developer: PL/SQL Programming Chapter 5 Procedures

117 Chapter Objectives After completing this lesson, you should be able to understand: Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure in SQL*Plus Using the IN OUT parameter Calling procedures from other blocks Using the DESCRIBE command with procedures Oracle10g Developer: PL/SQL Programming

118 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Debugging procedures using DBMS_OUTPUT Identifying useful software utilities for PL/SQL Using subprograms The scope of exception handling and transactions Using RAISE_APPLICATION_ERROR for error handling Removing procedures Oracle10g Developer: PL/SQL Programming

119 Brewbean’s Challenge Develop programming modules for specific tasks such as calculating taxes or updating inventory Oracle10g Developer: PL/SQL Programming

120 Named Program Units PL/SQL blocks executed thus far have been anonymous blocks Now we will assign a name to the block and save it in the database as a stored program unit This makes program units reusable Oracle10g Developer: PL/SQL Programming

121 Types of Program Units Oracle10g Developer: PL/SQL Programming
Program Unit Type Description Stored Procedures and Functions Performs a task such as calculation of shipping cost. Can receive input values and return values to the calling program. Called explicitly from a program. Stored in the Oracle9i database. Application Procedures and Functions* Same as Stored Procedures and Functions except these are saved in an Oracle9i application or library on the client-side. Package A module used to group together related procedures and functions. Called explicitly from a program. Stored on the server side. Database Trigger Performs a task automatically when a DML action occurs on the table with which it is associated. Stored in the Oracle9i database. Application Trigger* Performs a task automatically when a particular application event occurs such as the user clicking a button on the screen. Stored in an Oracle9i application. Oracle10g Developer: PL/SQL Programming

122 Parameters – Make Program Units Reusable
Mechanisms used to send values in and out of program units MODE DESCRIPTION IN Default if no mode is indicated. Passes a value from the application environment into the procedure. This value is considered a constant, as it cannot be changed within the procedure. OUT Passes a value out of the procedure to the application environment. If values are calculated or retrieved from the database within the procedure, OUT parameters are used to return these values to the calling environment. IN OUT Allows a value to be passed in and out using the same parameter. The values sent out can be different than the value sent in. Oracle10g Developer: PL/SQL Programming

123 Create Procedure Statement Syntax
Oracle10g Developer: PL/SQL Programming

124 Create Procedure Execution
Procedure to determine shipping cost Forward slash on last line to execute Note: Slash not needed for the Internet SQL*Plus interface Oracle10g Developer: PL/SQL Programming

125 Execute the Procedure Declare a host variable Use the SQL*Plus EXECUTE command Use the SQL*Plus PRINT command to view the host variable value Note: Parameter arguments are passed positionally Oracle10g Developer: PL/SQL Programming

126 SHOW ERRORS Command Error indicating parameter size Compilation Error
Displays error message Oracle10g Developer: PL/SQL Programming

127 Named Association Method
Provide parameter values by position (default) or name Pass arguments by parameter name in execution Oracle10g Developer: PL/SQL Programming

128 IN OUT mode Send value in and out via the same parameter
CREATE OR REPLACE PROCEDURE phone_fmt_sp (p_phone IN OUT VARCHAR2) IS BEGIN p_phone := '(' || SUBSTR(p_phone,1,3) || ')' || SUBSTR(p_phone,4,3) || '-' || SUBSTR(p_phone,7,4); END; / Oracle10g Developer: PL/SQL Programming

129 Calling a Procedure from a Block
Call to the ship_cost_sp procedure Oracle10g Developer: PL/SQL Programming

130 Variable Scope When nesting blocks, are variables shared?
Inner blocks can use variables from outer blocks Oracle10g Developer: PL/SQL Programming

131 Variable Scope (continued)
Oracle10g Developer: PL/SQL Programming

132 DESCRIBE Command Lists the parameters of a program unit
Oracle10g Developer: PL/SQL Programming

133 Debugging in SQL*Plus Use DBMS_OUTPUT.PUT_LINE statements to display messages from execution Must set SERVEROUTPUT ON Place display messages throughout the block to determine processing flow and variable values Oracle10g Developer: PL/SQL Programming

134 Other Software Utilities
Other utilities provide additional functionality to assist in PL/SQL development such as color-coded syntax and step debugging List of some popular third-party tools in Chapter 1 Oracle10g Developer: PL/SQL Programming

135 Subprograms A program unit defined within another program unit
Must be declared in the DECLARE section of the containing program unit Can only be referenced by the containing program unit Oracle10g Developer: PL/SQL Programming

136 Transaction Scope The scope refers to the group of DML statements that are affected by a particular transaction control statement By default, a session has a single DML queue and a transaction control statement would affect all DML in the queue regardless of which program unit initiated the statement DML statements of a program unit can be treated separately or as an autonomous transaction Oracle10g Developer: PL/SQL Programming

137 Autonomous Transaction
Indicates contained DML statements are autonomous COMMIT will only affect the INSERT in this program unit Oracle10g Developer: PL/SQL Programming

138 RAISE_APPLICATION_ERROR
Oracle10g Developer: PL/SQL Programming

139 RAISE_APPLICATION_ERROR (continued)
Oracle10g Developer: PL/SQL Programming

140 Remove a Procedure DROP PROCEDURE procedure_name;
Oracle10g Developer: PL/SQL Programming

141 Summary Named program unit assigns a name to a program unit so it can be reused Parameters are used to pass values in and out of program units Stored program units are saved in the database Parameter modes include: IN, OUT, and IN OUT Use DBMS_OUTPUT.PUT_LINE statement to debug Autonomous transactions must be explicitly created Oracle10g Developer: PL/SQL Programming

142 Oracle10g Developer: PL/SQL Programming Chapter 6 Functions

143 Chapter Objectives After completing this lesson, you should be able to understand: Functions Creating a stored function in SQL*Plus Using OUT parameters in functions Including multiple RETURN statements in a function Using a RETURN statement in a procedure Using constraints of actual and formal parameters Oracle10g Developer: PL/SQL Programming

144 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Understanding and controlling the passing of parameter values Working with function purity levels Referencing the data dictionary for program units Deleting program units Oracle10g Developer: PL/SQL Programming

145 Brewbean’s Challenge Need program module to check a user login
Oracle10g Developer: PL/SQL Programming

146 Brewbean’s Challenge (continued)
Need program module to calculate shipping cost based on the number of items in the basket Oracle10g Developer: PL/SQL Programming

147 Introduction to Functions
A function is similar to a procedure in that it can accomplish a task and retrieve/return values A function is part of an expression, not an entire statement such as a procedure Can be used in both PL/SQL and SQL statements Same as Oracle-supplied functions (ROUND, TO_CHAR) Contains a RETURN statement Oracle10g Developer: PL/SQL Programming

148 Example of Oracle-Supplied Function
SELECT idProduct, price, ROUND(price, 0) FROM bb_product WHERE idProduct < 4; Oracle10g Developer: PL/SQL Programming

149 Function Create Statement
Oracle10g Developer: PL/SQL Programming

150 Function Example Shipping cost Oracle10g Developer: PL/SQL Programming

151 Invoking a Function from a Block
An assignment statement is used – a function RETURNS a value! Oracle10g Developer: PL/SQL Programming

152 Attempt to Invoke Stand-alone
Oracle10g Developer: PL/SQL Programming

153 Use Function in SQL Oracle10g Developer: PL/SQL Programming

154 Brewbean’s Member Display
CREATE OR REPLACE FUNCTION memfmt1_sf (p_id IN NUMBER, p_first IN VARCHAR2, p_last IN VARCHAR2) RETURN VARCHAR2 IS lv_mem_txt VARCHAR2(35); BEGIN lv_mem_txt := 'Member '||p_id||' - '||p_first||' '||p_last; RETURN lv_mem_txt; END; Oracle10g Developer: PL/SQL Programming

155 Using OUT Mode in a Function
OUT parameters are not typically used in functions, as: Mixing OUT and RETURN values can lead to confusion It prohibits the function from being used in SQL Oracle10g Developer: PL/SQL Programming

156 Multiple RETURN Statements
Note: Only one RETURN statement can execute Oracle10g Developer: PL/SQL Programming

157 RETURN Statement in a Procedure
Different purpose than a RETURN statement in a function Used to change flow of execution Stops processing in that block and moves to the next statement after the procedure call Stand-alone statement with no arguments Oracle10g Developer: PL/SQL Programming

158 Parameter Constraints
Formal parameters – included in a program unit Actual parameters – arguments used in a program unit call Argument for an OUT parameter must be a variable to hold the value returned Actual parameters determine the size of the formal parameters Oracle10g Developer: PL/SQL Programming

159 Passing Parameter Values
Two techniques used to pass values between actual and formal parameters: Passed by Reference – create pointer to value in the actual parameter Passed by Value – copies value from actual to formal parameter Pass by value is the default Use a compiler hint to use pass by reference Oracle10g Developer: PL/SQL Programming

160 Pass by Reference Compiler Hint
Oracle10g Developer: PL/SQL Programming

161 Purity Levels Restrictions on functions used in SQL
Functions cannot modify any tables in Oracle8 and prior versions Beginning with Oracle8i, the function cannot modify a table used in the SQL statement that calls the function; however, it may alter other tables if called from a non-select statement If used in a remote or parallel operation, no reading or writing of packaged variables allowed If used in a SELECT, VALUES, or SET clause, the function can write values to packaged variables; otherwise, it is not allowed Oracle10g Developer: PL/SQL Programming

162 Purity Levels (continued)
Restrictions on functions used in SQL (continued) Functions cannot be used in a check constraint or as a default value of a table column If the function calls other subprograms, the subprograms cannot break these rules Must be a stored database object (or in a stored package) Can use only IN parameters Oracle10g Developer: PL/SQL Programming

163 Purity Levels (continued)
Restrictions on functions used in SQL (continued) Formal parameter data types must use database data types (no PL/SQL data types such as BOOLEAN are permitted) Return data types must be a database data type Must not issue transaction control statements to end the current transaction prior to execution Cannot issue ALTER SESSION or ALTER SYSTEM commands Oracle10g Developer: PL/SQL Programming

164 Purity Levels (continued)
Level Acronym Level Name Level Description WNDS Writes No Database State Function does not modify any database tables (No DML) RNDS Reads No Database State Function does not read any tables (No select) WNPS Writes No Package State Function does not modify any packaged variables (packaged variables are variables declared in a package specification; they are discussed in detail in Chapter 6) RNPS Reads No Package State Function does not read any packaged variables Oracle10g Developer: PL/SQL Programming

165 Data Dictionary Information
DESCRIBE identifies parameters and return value data type Oracle10g Developer: PL/SQL Programming

166 Data Dictionary Information (continued)
View source code using USER_SOURCE Oracle10g Developer: PL/SQL Programming

167 Delete Functions DROP FUNCTION function_name;
Oracle10g Developer: PL/SQL Programming

168 Summary Functions can be used in PL/SQL and SQL statements
A function is part of an expression Functions include parameters and must return a value OUT parameter rarely used Pass parameter values by value or reference Oracle10g Developer: PL/SQL Programming

169 Summary (continued) Actual versus formal parameters Purity levels
Formal parameters – included in a program unit Actual parameters – arguments used in a program unit call Purity levels USER_SOURCE view Oracle10g Developer: PL/SQL Programming

170 Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages

171 Chapter Objectives After completing this lesson, you should be able to understand: Creating package specifications Creating package bodies Invoking packaged program units Identifying public versus private construct scope Testing global construct value persistence Oracle10g Developer: PL/SQL Programming

172 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Including a forward declaration Creating one time only procedures Overloading packaged program units Managing restrictions on packaged functions used in SQL Using a cursor variable in a package Oracle10g Developer: PL/SQL Programming

173 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Determining execution privileges Identifying data dictionary information regarding packages Deleting or removing packages Oracle10g Developer: PL/SQL Programming

174 Packages Containers that can hold multiple program units
Add functionality Private program units Sharing variable values Overloading Ease privilege granting Improve performance Oracle10g Developer: PL/SQL Programming

175 Brewbean’s Challenge Organize the many program units developed for the application Store values throughout a user session Enable a program unit to handle different data types for arguments Ease the granting of privileges to users Oracle10g Developer: PL/SQL Programming

176 Package Specification
Contains declarations for program units, variables, exceptions, cursors, and types Declare program units with the header only Order of declarations important if one construct refers to another in the specification Oracle10g Developer: PL/SQL Programming

177 Package Specification (continued)
Oracle10g Developer: PL/SQL Programming

178 Package Body Contains the entire program unit code for those declared in the specification Use program unit name in END statement to make more readable Also can declare any new constructs not in the specification; however, these can only be used inside this package Oracle10g Developer: PL/SQL Programming

179 Invoking Package Constructs
Call packaged program units the same way as we handled stand-alone program units except add a package name prefix package_name.program_unit_name(args,…); Reference other packaged constructs such as a variable also using a package name prefix package_name.variable_name Oracle10g Developer: PL/SQL Programming

180 Package Construct Scope
Any constructs declared in the specification are public and can be referenced from inside or outside the package Any constructs in the body only are private and can only be referenced by other constructs within the same package body Oracle10g Developer: PL/SQL Programming

181 Package Global Constructs
Constructs declared in the specification such as variables, cursors, types, and exceptions are global Global means that the value will persist throughout a user session Each user session maintains a separate instance of the packaged construct Oracle10g Developer: PL/SQL Programming

182 Package Global Constructs (continued)
Oracle10g Developer: PL/SQL Programming

183 Package Specification
A specification can exist without a body Used to store often referenced static values Example CREATE OR REPLACE PACKAGE metric_pkg IS cup_to_liter CONSTANT NUMBER := .24; pint_to_liter CONSTANT NUMBER := .47; qrt_to_liter CONSTANT NUMBER := .95; END; Oracle10g Developer: PL/SQL Programming

184 Improving Processing Efficiency
Packaged constructs such as variables and cursors are stored in memory After the initial call, values can then be retrieved from cache in subsequent calls Package code is also cached Oracle10g Developer: PL/SQL Programming

185 Forward Declarations Private program units must be ordered so that any referenced unit is located prior to the calling program unit in the package body You need a workaround if you want to organize program units in the body Forward declarations eliminate the order problem A forward declaration is the program unit header at the top of the package body Oracle10g Developer: PL/SQL Programming

186 One Time Only Procedure
Used when user needs a dynamic action to occur on the initial call to a package It is an anonymous block placed at the end of a package body (no END statement!) Only executes on initial call to the package Typically used to populate global constructs Oracle10g Developer: PL/SQL Programming

187 Overloading Program Units
Overloading is the creation of more than one program unit with the same name The program units must differ by at least one of the following: Number of parameters Parameter data type families Listed order Oracle10g Developer: PL/SQL Programming

188 Overloading Program Units (continued)
Allows a particular program unit to accept various sets of arguments Some Oracle-supplied functions are overloaded, such as TO_CHAR, which can accept various data types as an argument Overloading can only be accomplished with a package Oracle10g Developer: PL/SQL Programming

189 Packaged Function Restrictions
Function purity level defines what structures the function reads or modifies Important to indicate purity level in package specification to discover errors at compile time rather than run time Add the following statement in the specification: PRAGMA RESTRICT_REFERENCES(program_unit_name, purity levels,…) Oracle10g Developer: PL/SQL Programming

190 Purity Levels Level Acronym Level Name Level Description WNDS
Writes No Database State Function does not modify any database tables (No DML) RNDS Reads No Database State Function does not read any tables (No select) WNPS Writes No Package State Function does not modify any packaged variables (packaged variables are variables declared in a package specification) RNPS Reads No Package State Function does not read any packaged variables Oracle10g Developer: PL/SQL Programming

191 Execute Privileges Avoids issuing privileges to all database objects
If you issue EXECUTE privilege on a package, the user will assume the package owner rights for the period of execution Called definer-rights You can override this default by adding AUTHID CURRENT_USER in the specification Adds security by avoiding the direct access issue of privileges to database objects Oracle10g Developer: PL/SQL Programming

192 Data Dictionary Information
Text column of USER_SOURCE view will display the source code of the entire package – specification and body Use a WHERE clause on the name column to select only one package The USER_OBJECTS view can be used to determine what packages exist in the database Oracle10g Developer: PL/SQL Programming

193 Deleting Packages To delete specification and body:
DROP PACKAGE package_name; To delete the body only: DROP PACKAGE BODY package_name; Oracle10g Developer: PL/SQL Programming

194 Summary A package can have two parts: a specification and a body
Packages allow both public and private constructs Global construct values persist Forward declaration enables program unit organization One time only procedures only execute on the initial call to the package Oracle10g Developer: PL/SQL Programming

195 Summary (continued) Overloading allows program units to accept different sets of arguments Indicate function purity levels with the PRAGMA RESTRICT_REFERENCES statement Granting the EXECUTE privilege on a package enables definer-rights The USER_SOURCE data dictionary view is used to retrieve package source code The DROP statement is used to delete packages Oracle10g Developer: PL/SQL Programming

196 Chapter 8 Program Unit Dependencies Oracle10g Developer:
PL/SQL Programming Chapter 8 Program Unit Dependencies

197 Chapter Objectives After completing this lesson, you should be able to understand: Local program unit dependencies Direct and indirect dependencies Data dictionary information concerning dependencies Running the dependency tree utility Oracle10g Developer: PL/SQL Programming

198 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Identifying the unique nature of package dependencies Remote object dependency actions Using remote dependency invalidation methods Avoiding recompilation errors Granting program unit privileges Oracle10g Developer: PL/SQL Programming

199 Program Unit Dependencies
Relationships or dependencies determine the validity of any program unit after modifications to database objects that the program unit references This validity determines the need for recompilation A procedure calls a function The procedure is a dependent object and the function is the referenced object Oracle10g Developer: PL/SQL Programming

200 Brewbean’s Challenge Need to take any steps possible to make the execution more efficient Users have been hitting some unexpected errors related to recent modifications to the database and program units In this light, need to review database dependencies and their impact Oracle10g Developer: PL/SQL Programming

201 Local Dependency Activity
Status of program unit can be checked using USER_OBJECTS When a referenced object is modified, the status of the dependent object changes to INVALID INVALID status indicates need for recompilation ALTER COMPILE command used to recompile a program unit Oracle10g Developer: PL/SQL Programming

202 Automatic Recompilation
Upon execution of a program unit with an INVALID status, the system will automatically recompile Drawbacks Recompilation of dependent objects tests the changes to the referenced objects, which could raise errors at run time Recompilation processing occurs during run time Oracle10g Developer: PL/SQL Programming

203 Direct & Indirect Dependencies
Direct – a procedure calls a function Indirect – a procedure calls a procedure which calls a function The dependency between the first procedure and the function is indirect Indirect dependencies have same affect as direct dependencies Oracle10g Developer: PL/SQL Programming

204 Data Dictionary USER_DEPENDENCIES identify direct dependencies
Use WHERE clause on name column to analyze a particular object DBA_DEPENDENCIES will identify direct dependencies of objects in all schemas Oracle10g Developer: PL/SQL Programming

205 Dependency Tree Utility
Mechanism to map direct and indirect dependencies Execute utldtree.sql script once to set up the feature Deptree_fill procedure used to analyze an object Two views Deptree: numeric scheme Ideptree: indented scheme Oracle10g Developer: PL/SQL Programming

206 Package Dependencies Modifications to package specification will change status of dependent objects Modifications to only the package body do NOT change status of dependent objects Separation of code in packages Minimizes recompilation needs Dependent objects to be developed prior to the package body being created Oracle10g Developer: PL/SQL Programming

207 Remote Object Dependencies
Database links are used to connect to other Oracle databases Links allow calls to objects in other databases These objects are called remote objects When remote objects are modified, local dependent objects are not initially flagged as INVALID Remote dependencies are not checked until run time Oracle10g Developer: PL/SQL Programming

208 Remote Invalidation Methods
Timestamp: compares the last date of modification of dependent and referenced objects Signature: compares the parameter modes, data types, and order Timestamp is the default method Databases in different time zones generate unnecessary recompilation using the timestamp method Oracle10g Developer: PL/SQL Programming

209 Avoiding Recompilation Errors
Use %TYPE and %ROWTYPE attributes Use the ‘*’ notation in queries to select all columns Use a column list in INSERT statements Oracle10g Developer: PL/SQL Programming

210 Program Unit Privileges
System Privilege Explanation CREATE PROCEDURE Allows a user to create, modify, and drop program units within their own schema. CREATE ANY PROCEDURE Allows a user to create program units in any schema. Does not allow the modification or dropping of the program units. ALTER ANY PROCEDURE Allows a user to modify program units in any schema. DROP ANY PROCEDURE Allows a user to drop program units in any schema. EXECUTE ON program_unit_name Allows a user to execute a specific program unit. EXECUTE ANY PROCEDURE Allows a user to execute program units in any schema. Oracle10g Developer: PL/SQL Programming

211 Privileges - Data Dictionary
View Name Description SESSION_PRIVS Shows all privileges of the current schema, direct and indirect SESSION_ROLES Shows all roles granted to the current schema USER_SYS_PRIVS Shows only direct privileges of the current schema USER_ROLE_PRIVS Shows only direct roles granted to the current schema Oracle10g Developer: PL/SQL Programming

212 Summary Program unit status changes when referenced object is modified
INVALID status indicates a need for recompilation Direct and indirect dependencies both affect status Dependency tree utility allows mapping of both direct and indirect dependencies Oracle10g Developer: PL/SQL Programming

213 Summary (continued) Packages minimize recompilation needs
Remote dependencies do not update status until run time Appropriate privileges needed to create and use program units Oracle10g Developer: PL/SQL Programming

214 Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers

215 Chapter Objectives After completing this lesson, you should be able to understand: Database triggers and syntax How to create and test a DML trigger in SQL*Plus How to create and test an Instead Of database trigger Using system triggers Oracle10g Developer: PL/SQL Programming

216 Chapter Objectives (continued)
After completing this lesson, you should be able to understand (continued): Identifying when triggers should be used Identifying trigger restrictions Using the ALTER TRIGGER statement Deleting a trigger Using data dictionary information relevant to triggers Oracle10g Developer: PL/SQL Programming

217 Database Trigger Defined
Triggers are similar to procedures and functions but will execute automatically based on an event Events are either DML statements or database system actions Triggers will fire regardless of the source of the event DML triggers are specifically associated with a table or view Oracle10g Developer: PL/SQL Programming

218 Brewbean’s Challenge Update product inventory upon order completion
Oracle10g Developer: PL/SQL Programming

219 Create DML Trigger Syntax
Oracle10g Developer: PL/SQL Programming

220 Example Trigger 1 CREATE OR REPLACE TRIGGER product_inventory_trg
AFTER UPDATE OF orderplaced ON bb_basket FOR EACH ROW WHEN (OLD.orderplaced <> 1 AND NEW.orderplaced = 1) 5 DECLARE 6 CURSOR basketitem_cur IS SELECT idproduct, quantity, option1 FROM bb_basketitem WHERE idbasket = :NEW.idbasket; lv_chg_num NUMBER(3,1); 11 BEGIN FOR basketitem_rec IN basketitem_cur LOOP IF basketitem_rec.option1 = 1 THEN lv_chg_num := (.5 * basketitem_rec.quantity); ELSE lv_chg_num := basketitem_rec.quantity; END IF; UPDATE bb_product SET stock = stock – lv_chg_num WHERE idproduct = basketitem_rec.idproduct; END LOOP; 22 END; Oracle10g Developer: PL/SQL Programming

221 Trigger Timing AFTER or BEFORE event ROW level or STATEMENT level
WHEN clause provides conditional processing Oracle10g Developer: PL/SQL Programming

222 Trigger Event INSERT, UPDATE, DELETE OF column_name option
Use the OR operator to include more than one event in a trigger OF column_name option ON table_name Oracle10g Developer: PL/SQL Programming

223 Correlation Identifiers
Special bind variables associated with DML activity OLD and NEW by default DML Event OLD Identifier NEW Identifier INSERT Not available Contains insert values UPDATE Contains values of the original row Contains new value for any columns updated and original values for any columns not updated DELETE Not Available (Note: "Not Available" indicates any references would retrieve a NULL value) Oracle10g Developer: PL/SQL Programming

224 Trigger Body PL/SQL block
Must include a DECLARE clause if declarations needed Can reference correlation identifiers using a preceding colon Can include calls to other program units Oracle10g Developer: PL/SQL Programming

225 Conditional Predicates
IF INSERTING, IF UPDATING, IF DELETING Supports different processing to occur for each type of DML statement since multiple DML actions can fire a trigger Can specify a specific column also: IF UPDATING (‘lastname’) THEN… Oracle10g Developer: PL/SQL Programming

226 Create Trigger in SQL*Plus
Oracle10g Developer: PL/SQL Programming

227 Instead Of Trigger Workaround for nonmodifiable view limitations
DML activity on a view will fire an Instead Of trigger DML activity in the trigger will execute against the base tables using values from the triggering event Oracle10g Developer: PL/SQL Programming

228 Instead Of Example Oracle10g Developer: PL/SQL Programming

229 System Triggers DDL and database system events
CREATE RENAME COMMENT ALTER TRUNCATE ASSOCIATE STATISTICS DROP ANALYZE DISASSOCIATE STATISTICS GRANT AUDIT REVOKE NOAUDIT Oracle10g Developer: PL/SQL Programming

230 System Trigger Syntax CREATE [OR REPLACE] TRIGGER trigger_name [BEFORE, AFTER] [List of DDL or Database System Events] [ON DATABASE | SCHEMA] Trigger body; ON DATABASE – will cause trigger to fire regardless of schema in which the trigger event originated ON SCHEMA – only fires when event occurs in the same schema in which the trigger was created Oracle10g Developer: PL/SQL Programming

231 System Trigger Example
Oracle10g Developer: PL/SQL Programming

232 Applying Triggers Oracle10g Developer: PL/SQL Programming Task Type
How a Trigger May be Applied Auditing Log files of database activity are widely used. An example would be tracking sensitive data modifications such as employee payroll data. A trigger could be used to write the original and new values of the employee salary update to an audit table. If any questions arise concerning the change, a record of the original values and new values assigned is now available. Data integrity Simple data validity checks can be accomplished with CHECK constraints. However, more complex checks or checks that require comparison to a live data value from the database can be accomplished using triggers. A trigger could be used to ensure that any changes to the regular price of a product do not allow a decrease from the current price. The NEW and OLD price values can be compared in a trigger. Referential integrity Foreign key constraints are used to enforce relationships between tables. If a parent key value is modified, such as a department number, a foreign key error occurs if we still have products assigned to that department. Triggers provide a way to avoid this error and accomplish a cascade update action. Oracle10g Developer: PL/SQL Programming

233 Applying Triggers (continued)
Task Type How a Trigger May be Applied Derived data We may have columns that hold values that are derived from using other columns in a calculation. For example, Brewbean's may have a product sales summary table that holds the total quantity and dollar sales by product. If this table needs to be updated in real time, then a trigger could be used. Every time a new sale is recorded, the trigger would fire and add the new sales amounts to the totals in the sales summary table. Security Additional checks on database access can be accomplished such as a simple check on the time of user logon. Some companies use a trigger to determine if it is a weekend day; if so, access is denied. In this case, the company identifies any weekend access as suspicious. (Don’t we wish all companies were like this?!!) Oracle10g Developer: PL/SQL Programming

234 Restrictions on Triggers
Cannot issue transaction control statements Cannot use LONG or LONG RAW data types Mutating Table error – attempt to modify a table in a row level trigger that is already being modified by the firing event Constraining table – table referenced via a foreign key of the table being modified in a trigger firing event Oracle10g Developer: PL/SQL Programming

235 ALTER TRIGGER statement
Used to compile or disable/enable a trigger ALTER TRIGGER trigger_name COMPILE; ALTER TRIGGER trigger_name DISABLE|ENABLE; ALTER TABLE table_name DISABLE|ENABLE ALL TRIGGERS; Oracle10g Developer: PL/SQL Programming

236 Delete a Trigger DROP TRIGGER trigger_name;
Note: If a table or view is dropped, any associated DML triggers will automatically be deleted Oracle10g Developer: PL/SQL Programming

237 Data Dictionary Same as other program units except for viewing the source code USER_TRIGGERS to view trigger source code Description column contains the header code Trigger_body column contains the body code Oracle10g Developer: PL/SQL Programming

238 Summary Database triggers fire implicitly based on a DML event or a system event Timing options include BEFORE, AFTER, ROW, and STATEMENT level WHEN clause provides conditional processing of a trigger Correlation identifiers allow referencing values involved in the DML action Oracle10g Developer: PL/SQL Programming

239 Summary (continued) Conditional predicates allow different processing for each type of DML action Instead Of triggers provide a mechanism to handle DML activity on nonmodifiable views The ALTER TRIGGER command allows a trigger to be compiled or ENABLED/DISABLED The USER_TRIGGERS data dictionary view allows the display of trigger code Oracle10g Developer: PL/SQL Programming

240 Chapter 10 Oracle10g Developer: PL/SQL Programming
Oracle-Supplied Packages and SQL*Loader

241 Objectives After completing this lesson, you should be able to understand: Using communications packages Generating output via packages Including large objects in the Oracle database Exploring dynamic SQL and PL/SQL Identifying other important built-in packages Using the SQL*Loader utility Oracle10g Developer: PL/SQL Programming

242 Brewbean’s Challenge Credit card verification Real-time messages
generation Import external file data Include image files in the database Schedule program execution Oracle10g Developer: PL/SQL Programming

243 Communications Packages
Built-in Package Name Description Script Filename DBMS_PIPE Allows different database sessions to communicate dbmspipe.sql DBMS_ALERT Enables notification of database events dbmsalrt.sql UTL_SMTP Enables features utlsmtp.sql Oracle10g Developer: PL/SQL Programming

244 DBMS_PIPE Allows different sessions in the same instance to communicate Uses buffers in the SGA Typically used to interface with the operating system or an external system Sending a message is a two-step process of packing and sending Oracle10g Developer: PL/SQL Programming

245 DBMS_PIPE Example Oracle10g Developer: PL/SQL Programming

246 DBMS_ALERT Allows real-time messages or alerts to be sent to users upon a particular event Accomplished in a database trigger to be associated with an event An example use is online auctions Process includes: register an alert name, set when alert should signal, and identify users that should be recipients Oracle10g Developer: PL/SQL Programming

247 DBMS_ALERT Example DBMS_ALERT.REGISTER(‘new_bid’);
Register name DBMS_ALERT.REGISTER(‘new_bid’); Fire signal in database trigger DBMS_ALERT.SIGNAL(‘new_bid’, TO_CHAR(:new.bid)); Register recipient DBMS_ALERT.WAITONE(‘new_bid’, v_msg, v_status, 600); Oracle10g Developer: PL/SQL Programming

248 UTL_MAIL Simplifies sending e-mail via a PL/SQL block
Introduced in Oracle10g Scripts must be executed to set up the package SMTP server must be defined on the system Oracle10g Developer: PL/SQL Programming

249 UTL_MAIL Example Oracle10g Developer: PL/SQL Programming

250 UTL_SMTP Simplifies e-mail generation
Simple Mail Transfer Protocol (SMTP) used to send s Programmatically create all the parts of an Used to communicate with customers, suppliers, and internal employees as appropriate Oracle10g Developer: PL/SQL Programming

251 UTL_SMTP Oracle10g Developer: PL/SQL Programming Function Name
Description HELO Performs initial handshaking to identify the sender to the mail server MAIL Initiates a mail transaction which sends messages to mailbox destinations RCPT Identifies each of the recipients of an DATA Specifies the lines in the body of an RSET Aborts the current mail transaction NOOP Requests a reply from the mail server to verify connection is still alive QUIT Terminates the SMTP session and disconnects from the mail server OPEN_CONNECTION Opens a connection to the mail server OPEN_DATA Sends the DATA command WRITE_DATA Adds data to message body CLOSE_DATA Ends the message Oracle10g Developer: PL/SQL Programming

252 UTL_HTTP Used to analyze HTML source of Web pages
Makes Hypertext Transfer Protocol (HTTP) calls from within PL/SQL REQUEST_PIECES function will retrieve the HTML source of a specified URL in 2,000 byte segments Oracle10g Developer: PL/SQL Programming

253 UTL_TCP Allows low-level calls using TCP/IP
Internet communications rely on TCP/IP The UTL_SMTP and UTL_HTTP packages rely on this package Oracle10g Developer: PL/SQL Programming

254 Generating Output Oracle10g Developer: PL/SQL Programming
Built-in Package Name Description Script Filename DBMS_OUTPUT Displays data to the screen dbmsotpt.sql UTL_FILE Read and write data to external files utlfile.sql Oracle10g Developer: PL/SQL Programming

255 DBMS_OUTPUT Displays data from within PL/SQL code
Most popularly used for debugging In SQL*Plus, SET SERVEROUTPUT ON must be set The PUT procedure continues to place data on the same output line The PUT_LINE procedure will start a new line Oracle10g Developer: PL/SQL Programming

256 DBMS_OUTPUT Example Oracle10g Developer: PL/SQL Programming

257 UTL_FILE Enables reading and writing text data to operating system files (import and export data) Program Unit Name Description FOPEN Opens a file to write to or be read PUT_LINE Writes a line to a file GET_LINE Reads a line from a file FCLOSE Closes a file Oracle10g Developer: PL/SQL Programming

258 UTL_FILE Example Write to a file
Oracle10g Developer: PL/SQL Programming

259 UTL_FILE Example Read a file Oracle10g Developer: PL/SQL Programming

260 Large Objects (LOBs) Handle media such as images, video segments, and large documents LOB Type Description BLOB Binary large object such as a photo file CLOB Character large object such as text documentation BFILE Binary large object such as a streaming video or movie file NCLOB Fixed-width character data for storing character data in other languages Oracle10g Developer: PL/SQL Programming

261 LOBs Enable the storage of large objects as columns in a database table Can hold up to 4GB of data Multiple LOB columns allowed All except BFILE are stored internally in the database A LOB column contains pointer to actual LOB data Oracle10g Developer: PL/SQL Programming

262 DBMS_LOB Example Oracle10g Developer: PL/SQL Programming

263 Dynamic SQL and PL/SQL Allow construction and parsing of statements at run time Enable the execution of DDL statements from within PL/SQL Two mechanisms DBMS_SQL package Dynamic SQL Covered in Chapter 10 Oracle10g Developer: PL/SQL Programming

264 DBMS_JOB Enables jobs to be scheduled for execution
Program Unit Name Description BROKEN Flags the job as broken so it will not be executed CHANGE Alters job parameters set by a user INTERVAL Modifies execution interval for a job ISUBMIT Submits a job with a specified job number NEXT_DATE Modifies the next date of execution REMOVE Deletes job from the queue RUN Executes the specified job immediately SUBMIT Adds a job to the queue USER_EXPORT Creates text of call to recreate the job WHAT Modifies the PL/SQL code to be executed Oracle10g Developer: PL/SQL Programming

265 DBMS_JOB INIT.ORA settings SUBMIT procedure JOB_QUEUE_PROCESSES=1
JOB_QUEUE_INTERVAL=60 SUBMIT procedure PROCEDURE submit ( job OUT BINARY_INTEGER, what IN VARCHAR2, next_date IN DATE DEFAULT sysdate, interval IN VARCHAR2 DEFAULT 'null', no_parse IN BOOLEAN DEFAULT FALSE, instance IN BINARY_INTEGER DEFAULT 0, force IN BOOLEAN DEFAULT FALSE ); Oracle10g Developer: PL/SQL Programming

266 DBMS_JOB Example BEGIN DBMS_JOB.SUBMIT (job => :jobno,
what => 'BEGIN prod_sum_sp; END;', next_date => TRUNC(SYSDATE+1), interval => 'TRUNC(SYSDATE+1)' ); COMMIT; END; / Oracle10g Developer: PL/SQL Programming

267 DBMS_JOB Example (continued)
Oracle10g Developer: PL/SQL Programming

268 DBMS_DDL Allows access to two specific DDL statements: ALTER_COMPILE
ANALYZE_OBJECT Oracle10g Developer: PL/SQL Programming

269 Exploring More Search the OTN Web site for more Oracle-supplied packages Package Name Description DBMS_JAVA Controls the behavior of the Java Virtual Machine used to run Java stored procedures DBMS_METADATA Retrieves information about database objects DBMS_RANDOM Random number generator DBMS_SESSION Allows access to session options directly from PL/SQL DBMS_UTILITY Contains a miscellaneous group of programs ranging from capabilities to assist in procedure management to reporting error information DBMS_XMLGEN Converts data from an SQL query into XML UTL_HTTP Accesses Web pages UTL_INADDR Retrieves Internet site host name or IP address Oracle10g Developer: PL/SQL Programming

270 SQL*Loader Utility Client tool provided by Oracle
Simplifies loading data from a flat file into the database Can execute a large number of rows efficiently Can read data in many different formats Oracle10g Developer: PL/SQL Programming

271 SQL*Loader Utility (continued)
Involves three items A data file A control file that defines how the data should be read and loaded A command to execute the utility Oracle10g Developer: PL/SQL Programming

272 SQL*Loader Utility Example
Example data file for coffee suppliers "Reeding Trades",Brazil,25,2 "Beans Here, There, Everywhere",Ethiopia,,4 "Coffee Suppliers Inc.",Spain,20,1 "Traders First Beans",Costa Rica, 50,2 Oracle10g Developer: PL/SQL Programming

273 SQL*Loader Utility Example (continued)
Example control file LOAD DATA INFILE 'C:\vendors.csv' REPLACE INTO TABLE bb_vendor_list FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY ' "' TRAILING NULLCOLS (vname, v_cntry, min_lbs INTEGER EXTERNAL, ship_days INTEGER EXTERNAL) Oracle10g Developer: PL/SQL Programming

274 SQL*Loader Utility Example (continued)
Example command to execute sqlldr control=C:\vendors.ctl Oracle10g Developer: PL/SQL Programming

275 Summary Oracle-supplied packages are pre-built packages to address common processing needs DBMS_PIPE allows communication between sessions DBMS_ALERT enables event notification UTL_SMTP simplifies generation UTL_HTTP enables HTML source retrieval UTL_TCP enables TCP/IP communications Oracle10g Developer: PL/SQL Programming

276 Summary (continued) DBMS_OUTPUT allows data display
UTL_FILE enables reading and writing to text files DBMS_LOB manages LOBs DBMS_JOB provides job scheduling capabilities DBMS_DDL enables the COMPILE and ANALYZE commands to be processed within PL/SQL SQL*Loader utility enables loading data from external files Oracle10g Developer: PL/SQL Programming

277 Chapter 11 Oracle10g Developer: PL/SQL Programming
Introduction to Dynamic SQL and Object Technology

278 Chapter Objectives After completing this lesson, you should be able to understand: Creating dynamic SQL Using object technology Oracle10g Developer: PL/SQL Programming

279 Brewbean’s Challenge Add flexibility to queries, such as allowing shoppers to determine if they want to search product names or descriptions Explore potential capabilities of object technology features for providing greater data consistency and control Oracle10g Developer: PL/SQL Programming

280 Dynamic SQL Allows identifiers such as column and table names to be provided at run time Two mechanisms available DBMS_SQL package (Oracle7) Native dynamic SQL (Oracle8) Oracle10g Developer: PL/SQL Programming

281 DBMS_SQL – DML Example CREATE OR REPLACE PROCEDURE dyn_dml_sp
(p_col VARCHAR2, p_price NUMBER, p_id NUMBER) IS lv_cursor INTEGER; lv_update VARCHAR2(150); lv_rows NUMBER(1); BEGIN --Open Cursor lv_cursor := DBMS_SQL.OPEN_CURSOR; Oracle10g Developer: PL/SQL Programming

282 DBMS_SQL – DML Example (continued)
--Create DML statement lv_update := 'UPDATE bb_product SET ' || p_col || ' = :ph_price WHERE idProduct = :ph_id'; --Parse the statement DBMS_SQL.PARSE(lv_cursor, lv_update, DBMS_SQL.NATIVE); --Associate parameters with placeholders in the statement DBMS_SQL.BIND_VARIABLE(lv_cursor, ':ph_price', p_price); DBMS_SQL.BIND_VARIABLE(lv_cursor, ':ph_id', p_id); Oracle10g Developer: PL/SQL Programming

283 DBMS_SQL – DML Example (continued)
--Run the DML statement lv_rows := DBMS_SQL.EXECUTE(lv_cursor); --Close the cursor DBMS_SQL.CLOSE_CURSOR(lv_cursor); --Save changes COMMIT; --Check how many rows affected DBMS_OUTPUT.PUT_LINE(lv_rows); END; Oracle10g Developer: PL/SQL Programming

284 DBMS_SQL – DML Example (continued)
Oracle10g Developer: PL/SQL Programming

285 DBMS_SQL – Query Example
CREATE OR REPLACE PROCEDURE dyn_query1_sp (p_col IN VARCHAR2, p_value IN VARCHAR2) IS lv_query LONG; lv_status INTEGER; lv_cursor INTEGER; lv_col1 NUMBER(2); lv_col2 VARCHAR2(25); lv_col3 NUMBER(6,2); lv_col4 NUMBER(5,1); Oracle10g Developer: PL/SQL Programming

286 DBMS_SQL – Query Example (continued)
BEGIN --Open the cursor lv_cursor := DBMS_SQL.OPEN_CURSOR; --Build the query lv_query := 'SELECT idProduct, productname, price, stock FROM bb_product WHERE '|| UPPER(p_col) ||' = ' || 'UPPER(:ph_value)'; --Parse the statement DBMS_SQL.PARSE(lv_cursor, lv_query, DBMS_SQL.NATIVE); --Identify data types for each item selected DBMS_SQL.DEFINE_COLUMN(lv_cursor, 1, lv_col1); DBMS_SQL.DEFINE_COLUMN(lv_cursor, 2, lv_col2, 25); DBMS_SQL.DEFINE_COLUMN(lv_cursor, 3, lv_col3); DBMS_SQL.DEFINE_COLUMN(lv_cursor, 4, lv_col4); Oracle10g Developer: PL/SQL Programming

287 DBMS_SQL – Query Example (continued)
--Associate placeholder with a parameter DBMS_SQL.BIND_VARIABLE(lv_cursor, ':ph_value', p_value); --Execute the query lv_status := DBMS_SQL.EXECUTE(lv_cursor); --Fetch row returned and place into PL/SQL variables IF (DBMS_SQL.FETCH_ROWS(lv_cursor) > 0) THEN DBMS_SQL.COLUMN_VALUE(lv_cursor, 1, lv_col1); DBMS_SQL.COLUMN_VALUE(lv_cursor, 2, lv_col2); DBMS_SQL.COLUMN_VALUE(lv_cursor, 3, lv_col3); DBMS_SQL.COLUMN_VALUE(lv_cursor, 4, lv_col4); DBMS_OUTPUT.PUT_LINE(lv_col1||' '||lv_col2||' '||lv_col3||' '||lv_col4); END IF; --Close cursor DBMS_SQL.CLOSE_CURSOR(lv_cursor); END; Oracle10g Developer: PL/SQL Programming

288 DBMS_SQL – Query Example (continued)
Oracle10g Developer: PL/SQL Programming

289 Native Dynamic SQL Simpler coding More efficient processing
Limited capabilities compared to DBMS_SQL package Two methods EXECUTE IMMEDIATE OPEN FOR Oracle10g Developer: PL/SQL Programming

290 Native Dynamic SQL Example
CREATE OR REPLACE PROCEDURE dyn_query3_sp (p_col IN VARCHAR2, p_value IN VARCHAR2) IS lv_query VARCHAR2(200); lv_id bb_product.idProduct%TYPE; lv_name bb_product.productname%TYPE; lv_price bb_product.price%TYPE; lv_stock bb_product.stock%TYPE; BEGIN --use a variable to hold the query construction to -- make it more readable Oracle10g Developer: PL/SQL Programming

291 Native Dynamic SQL Example (continued)
lv_query := 'SELECT idProduct, productname, price, stock FROM bb_product WHERE UPPER(' || p_col || ') = UPPER(:ph_value)'; --Run the dynamic query supplying variables to hold the -- return values in the INTO clause and associate the -- parameter to the placeholder with the USING clause EXECUTE IMMEDIATE lv_query INTO lv_id, lv_name, lv_price, lv_stock USING p_value; DBMS_OUTPUT.PUT_LINE(lv_id||' '||lv_name||' ' ||lv_price||' '||lv_stock); END; Oracle10g Developer: PL/SQL Programming

292 Native Dynamic SQL Example (continued)
Oracle10g Developer: PL/SQL Programming

293 DBMS_SQL vs. Native Dynamic SQL
Use native dynamic SQL when: The number and types of columns to be used is known The number and type of bind variables is known To perform DDL Executing the statement only once or twice User-defined types such as object and collections are used (not supported by DBMS_SQL) Fetching rows of data into PL/SQL records (not supported by DBMS_SQL) SQL statement is less than 32KB in size Oracle10g Developer: PL/SQL Programming

294 Object Technology Object Types Object Methods Object Relations
Object Views Oracle10g Developer: PL/SQL Programming

295 Object Types Represent an entity such as an address or a person
Defined with attributes and methods Can be used as a data type for a table column Can contain multiple data elements or attributes Oracle10g Developer: PL/SQL Programming

296 Create an Object Type CREATE OR REPLACE TYPE addr_ot AS OBJECT
(street1 VARCHAR2(25), street2 VARCHAR2(25), city VARCHAR2(25), state CHAR(2), zip NUMBER(9) ); Oracle10g Developer: PL/SQL Programming

297 Use Object Type CREATE TABLE bb_order (ord_id NUMBER(4),
cust_id NUMBER(4), ord_date DATE, total NUMBER(6,2), bill_addr addr_ot, ship_addr addr_ot ); Oracle10g Developer: PL/SQL Programming

298 Object Type Constructor
DECLARE lv_bill addr_ot; lv_ship addr_ot; BEGIN lv_bill := addr_ot('11 Bush Dr' ,NULL, 'Savannah', 'GA', ); lv_ship := addr_ot('812 Scott Lane','Apt #52','Savannah','GA', ); INSERT INTO bb_order VALUES (102,31,'11-NOV-03’ ,34.50,lv_bill,lv_ship); END; Oracle10g Developer: PL/SQL Programming

299 DESCRIBE Command Oracle10g Developer: PL/SQL Programming

300 Methods Add program units to object types Referred to as members
Similar to package creation Add function ALTER TYPE addr_ot ADD MEMBER FUNCTION lbl_print RETURN VARCHAR2; Oracle10g Developer: PL/SQL Programming

301 Object Type Body Oracle10g Developer: PL/SQL Programming

302 Object Relations CREATE TYPE cust_ot AS OBJECT
Create customer object type CREATE TYPE cust_ot AS OBJECT (cust_id NUMBER(4), first VARCHAR2(15), last VARCHAR2(20), VARCHAR2(25), phone NUMBER(10) ); Create customer table CREATE TABLE bb_cust OF cust_ot (PRIMARY KEY (cust_id)); Oracle10g Developer: PL/SQL Programming

303 Object Relations (continued)
Create orders object type CREATE TYPE ord_ot AS OBJECT (ord_id NUMBER(4), cust_ref REF cust_ot, ord_date DATE, total NUMBER(6,2)); CREATE TABLE bb_ord OF ord_ot (PRIMARY KEY (ord_id)); Oracle10g Developer: PL/SQL Programming

304 Object Relations (continued)
Use REF variable to establish relation INSERT INTO bb_cust VALUES )); INSERT INTO bb_ord SELECT ord_ot(1,REF(c),SYSDATE,24.50) FROM bb_cust c WHERE cust_id = 12; COMMIT; Oracle10g Developer: PL/SQL Programming

305 REF Pointers Does not prevent broken relations like a foreign key constraint Oracle10g Developer: PL/SQL Programming

306 Object Views Provide a layer on top of traditional database designs to enable object features OBJECT OID identifies unique view row identifier CAST and MULTISET handle subquery mapping to view elements Oracle10g Developer: PL/SQL Programming

307 Object View Example CREATE TYPE bask_ot AS OBJECT (idBasket NUMBER(5),
total NUMBER(7,2)) / CREATE TYPE bask_tab AS TABLE OF bask_ot CREATE TYPE shop_ot AS OBJECT (idShopper NUMBER(4), last_name VARCHAR2(20), city VARCHAR2(20), idBasket bask_tab) Oracle10g Developer: PL/SQL Programming

308 Object View Example (continued)
CREATE VIEW shop_vu OF shop_ot WITH OBJECT OID(idShopper) AS SELECT s.idShopper, s.lastname, s.city, CAST(MULTISET(SELECT idBasket, total FROM bb_basket b WHERE b.idShopper = s.idShopper) AS bask_tab) FROM bb_shopper s; Oracle10g Developer: PL/SQL Programming

309 Summary Dynamic SQL allows identifiers and DDL statements to process within PL/SQL DBMS_SQL package and native dynamic SQL are two mechanisms providing dynamic SQL capabilities Native dynamic SQL is simpler to code and executes more efficiently Object types represent an entity that can contain multiple data attributes and program units Oracle10g Developer: PL/SQL Programming

310 Summary (continued) Program units in object types are called methods
Relationships between object rows are established using REF variables Object views provide a mechanism to use object technology features with a traditional database design Oracle10g Developer: PL/SQL Programming


Download ppt "Chapter 1 Introduction to PL/SQL Oracle10g Developer:"

Similar presentations


Ads by Google