Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć260 minutes Lecture 20 minutes Practice 80 minutes Total Class Management Note: Files required for lesson are: DEMO: l20
Trang 1Modularizing Programming with
Subprograms
20
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć2
60 minutes Lecture
20 minutes Practice
80 minutes Total
Class Management Note:
Files required for lesson are:
DEMO: l20proc.pls, l20func.pls
PRACTICE: p20proc.pls
Trang 3Modularity allows you to break your code into manageable, well-defined logical units Each of these units in PL/SQL is called a program unit, or a subprogram PL/SQL has two types of subprograms called procedures and functions This lesson covers the structure of subprograms and how to invoke them.
At the end of this lesson, you should be able to
D Determine the types of program units and where to use them
D Explain the differences between and benefits of procedures and functions
D Develop subprograms
D Invoke subprograms from Procedure Builder
Class Management Note:
This lesson is designed to give students an overview of a subprogrambecause Procedure Builder can only store subprograms, not anonymousblocks Therefore, use this lesson as a high level overview, with the details
to follow in the next lessons
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć4
Trang 5Program units are named PL/SQL blocks They fall into three main categories:
D Procedures to perform actions
D Functions to compute a value
D Packages to bundle logically related procedures and functions
Stored or Application Subprogram?
These program units can be created in a variety of environments, including
server-side stored subprograms or as application subprograms.
Concept Stored Subprogram Application Subprogram
Location Is in the database Is within the application
Executed From any database tool or
application
From only the application inwhich it was created
Availability By way of database security Independently of, and in
addition to, stored subprograms.Subprograms are composed of a number of sections:
D A header to name and type the block
D An optional declarative section to set up local identifiers
D An executable part to perform the actions
D An optional exception handling section to handle exceptions
For more information, see
PL/SQL User’s Guide and Reference, Release 2.3, “Subprograms.”
Class Management Note:
Packages and other PL/SQL constructs are covered in the Develop
Database Procedures course.
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć6
Trang 7Creating a Subprogram
The following steps will assist you to create a subprogram
1. Select your environment
If using Procedure Builder, then select either the Program Units node or theDatabase Objects node and Stored Procedures Units subobject node
2. Write your syntax.
If using Procedure Builder, enter the syntax in the Program Unit Editor If usingSQL*Plus, write your code in a text editor as a script file
3. Compile your code
The source code is complied into p-code If using Procedure Builder, click theCompile button If using SQL*Plus, start your file at the SQL prompt
4. Invoke the successfully compiled procedure or function
Guidelines
D SQL*Plus is another development environment for writing and for initial testing
of a procedure, although you will need to test the procedure by invoking it from
an application
D The SQL commands issued to create a stored subprogram are CREATE
PROCEDURE or CREATE FUNCTION
D The SQL commands issued to remove a stored subprogram are DROP
PROCEDURE or DROP FUNCTION
D Use CREATE OR REPLACE PROCEDURE or CREATE OR REPLACE
FUNCTION so you do not have to issue a DROP statement
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć8
Trang 9Creating a Procedure
Create a PL/SQL procedure to store a series of actions for later execution The
procedure can contain zero or more parameters, which are arguments that you listwhen calling the procedure
where: name is the procedure name, which adheres to the
standard Oracle naming rules
parameter is the parameter syntax shown below
pl/sql_block is the procedural body that defines the action
performed by the procedure
The parameter syntax is as follows.
Syntax
parameter_name [IN | OUT | IN OUT] datatype
[{:= | DEFAULT} expr]
where: parameter_name is the name of the parameter
datatype is the datatype of the parameter, without
constraints
expr is the value to initialize the parameter
Guidelines
D Start the PL/SQL block with the keyword IS
D Enter any local declarations between IS and BEGIN
When creating the procedure from Procedure Builder, the CREATE OR REPLACEportion of the syntax is implied Therefore, when creating the procedure from
SQL*Plus, begin the statement with CREATE OR REPLACE
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć10
Trang 11Creating a Procedure continuedProcedural Parameters
Transfer values to and from the calling environment through parameters There are
two types that you use When declaring a procedure, the formal parameter is used to define the values used in the executable portion of the PL/SQL block The actual parameter, or argument, is referenced when invoking a subprogram.
Parameter Modes for Formal Parameters
Parameter Mode Description
OUT Must be specified
Returns a value from the procedure to the callingenvironment
Formal parameter acts as an uninitialized variable.Formal parameter cannot be assigned to anothervariable or to itself
Actual parameter must be a variable; it cannot be aconstant or expression
IN OUT Must be specified
Passes a value from the calling environment into theprocedure, and returns a possibly different value fromthe procedure to the calling environment
Formal parameter acts as an initialized variable
Formal parameter can be used as a normal variable; itcan be assigned to a value
Actual parameter must be a variable
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć12
Class Management Note:
DEMO: l20proc.pls
PURPOSE: Demonstrate how to use the Procedure Builder environment,including loading and compiling code from a text file
1 Make sure you are connected to the database
2 Select from the menu File Load and load the file
3 Show students the code and Interpreter line command
You will invoke this procedure later in the lesson
Trang 13Creating a Procedure continued
Eliminate Unnecessary IN Arguments
D Where possible, derive values in the procedure, or use column default values
D Generate the primary key using a database sequence
D Record the username from the USER function
D Record the current date from the SYSDATE function
D Take advantage of business rules to compute input values automatically using aformula
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć14
Trang 15Comparing Functions and Procedures
A procedure can contain a list of parameters, but does not have to return a value It isinvoked in place of a complete PL/SQL statement A function differs from a
procedure in two ways:
D You invoke the function as part of an expression.
D A function must return a value.
SQL Functions
There are both user-defined functions, covered in this lesson, and SQL functions Youare already familiar with SQL functions You call the function with actual parametersfrom within a SQL command, such as SELECT
Example Number Functions
SYSDATE current date and time
s_dept_id.NEXTVAL database sequence value
A procedure containing one OUT argument can be rewritten as a function containing
a RETURN statement
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć16
Trang 17Creating a Function
Create a PL/SQL function to return a value to the calling environment You mustdeclare the RETURN datatype in the header section of the function definition, anddefine the value to be returned in the PL/SQL block You can also declare a list ofparameters to be passed into the function
where: name is the function name, which adheres to the
standard Oracle naming rules
parameter is the parameter syntax See the syntax in the
“Procedure” section of this lesson
datatype is the datatype of the value to be returned
pl/sql_block is the procedural body that defines the action
performed by the procedure
The RETURN Statement
Remember to include a RETURN statement in the PL/SQL block The function mustset the value of the return parameter and be of the same datatype specified in theRETURN clause of the function definition Multiple RETURN statements are
allowed, but only one will be executed by any one call Typically, the multiple
RETURN statements are within an IF statement
When creating the function from Procedure Builder, the CREATE OR REPLACEportion of the syntax is implied Therefore, when creating the function from
SQL*Plus, begin the statement with CREATE OR REPLACE
Class Management Note:
When creating a stored function in PL/SQL version 2.x, you can use either
IS or AS to begin you PL/SQL block Procedure Builder 1.5 uses PL/SQLversion 1.5 and does not support the use of the AS keyword
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć18
Class Management Note:
DEMO: l20func.pls
PURPOSE: Demonstrate how to use the Procedure Builder environment,including importing text from a text file
1 Click the Subprograms node
2 Click the Create button
3 Fill out the dialog box: name = tax, function type
4 Highlight all text
5 Import file l20func.pls into the Program Unit Editor.
6 Click the Compile button Note “Successfully Compiled”
7 Click the Close button
You will invoke this function later in the lesson
If using SQL*Plus, edit the file to include the words “CREATE OR
REPLACE” Start the file at the SQL*Plus command prompt to compile
Trang 19Creating a Function continued
Trang 20Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć20
Trang 21Invoking Subprograms
You can call procedures and functions from any tool or language that supports
PL/SQL From PL/SQL, you can call a procedure with a direct call, and call a
function as part of an expression
Invoking Procedures from Procedure Builder
Enter the procedure name with any actual parameters, if applicable, at the ProcedureBuilder Interpreter prompt Procedure Builder then performs the action specified inthe procedure
Example
Use the CHANGE_SALARY procedure to change the salary to 1000 for employeenumber 17
PL/SQL> change_salary (17, 1000);
Note: You may want to confirm the changes by issuing a SELECT statement.
Invoking Procedures from Another Procedure
The example on the facing page illustrates how you can invoke a procedure fromanother procedure In the example, procedure CHANGE_SALARY is being invokedfrom procedure PROCESS_SAL Similarly, you can invoke a function from a storedprocedure or a PL/SQL anonymous block
To invoke procedures from SQL*Plus, use the EXECUTE command Use SQL*Plusbind variables to hold returned values You can also use SQL*Plus substitutionvariables through the ampersand (&) and variable name
Class Management Note:
DEMO
PURPOSE: Demonstrate invoking the CHANGE_SALARY procedure
1 At the Interpreter prompt, show the current salary for
employee 17 Enter: SELECT id, salary FROM s_emp
WHERE id = 17;
2 Enter: change_salary (17, 1000);
3 To show that the salary was updated,
enter: SELECT id, salary FROM s_emp WHERE id = 17;
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć22
Class Management Note:
DEMO
PURPOSE: Demonstrate invoking the standalone TAX function
1 Create the variable to hold the return value of the function
At the Interpreter prompt,
enter: .CREATE NUMBER x PRECISION 4
Trang 23Invoking Subprograms continuedInvoking Standalone Functions
You can invoke a standalone function created in Procedure Builder First, you mustcreate a variable called the “identifier” to hold the returned value
Syntax
CREATE variable
where: variable is one of the following:
NUMBER var_name Specifies a variable, var_name, of the datatype [PRECISION number] NUMBER PRECISION determines the
[SCALE number] maximum number of objects SCALE
determines where rounding should occur
DATE var_name Specifies a variable, var_name, of the datatype
Display the tax based on a value Use the TAX function created earlier
PL/SQL> CREATE NUMBER x PRECISION 4
PL/SQL> :x := tax(100);
PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:x));
7
For more information, see
Procedure Builder Developer’s Guide, “Working with PL/SQL Constructs.”
Note: To invoke functions from SQL*Plus, use the EXECUTE command Use
SQL*Plus global variables to hold returned values You can also use
SQL*Plus substitution variables through the ampersand (&) and variablename To view the result, use the SQL*Plus PRINT command
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć24
Class Management Note:
Actual parameters to a PL/SQL function called from a SQL statement mustuse the positional notation for parameters
Trang 25Invoking Subprograms continuedInvoking Functions in SQL Statements
You can also call functions in SQL expressions Anywhere a built-in SQL functioncan be placed, a PL/SQL user-defined function can be placed as well
Advantages
D Permit calculations that are too complex, awkward, or unavailable with SQL
D Increase efficiency of queries by performing functions in the server rather than in
an application
Note: This feature is only available with PL/SQL 2.1 or higher and Oracle7 Server
release 7.1 or higher
Guidelines
D Only stored functions can be called from SQL statements, procedures cannot
D The function acts as a single-row function
D The function cannot contain a DML statement—the function cannot modifydatabase tables
D All formal parameters must be IN parameters; none can be an OUT or IN OUTparameter
D Datatypes used in the function must be Oracle7 Server internal datatypes, such asCHAR and DATE, not PL/SQL datatypes, such as BOOLEAN or RECORD
D The RETURN datatype must be an Oracle7 Server internal datatype
D You must own or have EXECUTE privileges on the PL/SQL function in order tocall it
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć26
Trang 27Invoking Subprograms continuedCalling a Function
You can call functions from any of these SQL clauses
D The select list of a SELECT command
D The condition of a WHERE and HAVING clause
D The CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses
D The VALUES clause of the INSERT command
D The SET clause of the UPDATE command
Example
Use the TAX function to calculate the tax on the total sale for order number 100
PL/SQL> SELECT total, tax(total)
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć28
Trang 29D Subprograms fall into three main categories:
D Procedures to perform actions
D Functions to compute a value
D Packages to bundle logically related procedures and functions
D A function differs from a procedure in two ways:
D You invoke the function as part of an expression
D A function must return a value
D Procedure and function components:
D Header—To name and type the block
D Declarative—To set up local identifiers (optional)
D Executable—To perform the actions
D Exception handling—To handle exceptions (optional)
D Invoke subprograms from the Procedure Builder Interpreter prompt
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 20Ć30