This module covered the creation of a function using PL/SQL blocks and SQL commands.
You learned the basic syntax of a function and reviewed a detailed account of creating an example. You created your own function for the course project and then used it within an UPDATE command. In addition, you practiced your documentation skills. Now that you completed this module, you should be able to:
- List the uses of a function and identify correct syntax
- Create and execute a function that returns a number, text, or date value
- List uses of a function that return a Boolean value
- Glossary:
In this module you were introduced to the following glossary terms:
- Function
- Stored function
There are two types of subprograms called procedures and functions, which can accept parameters and be invoked (called).
The SQL CREATE PROCEDURE statement lets you create standalone procedures that are stored in the database. The SQL CREATE FUNCTION statement lets you create standalone functions that are stored in an Oracle database. These stored (schema level) subprograms can be accessed from SQL. As shown in
Example 2, a subprogram is like a miniature program, beginning with a header followed by an
- optional declarative part,
- an executable part, and
- an optional exception-handling part.
Example 2: Creating a Stored Subprogram
-- including OR REPLACE is more convenient when updating a subprogram
CREATE OR REPLACE PROCEDURE award_bonus (emp_id NUMBER, bonus NUMBER) AS
commission REAL;
comm_missing EXCEPTION;
BEGIN -- executable part starts here
SELECT commission_pct / 100 INTO commission FROM employees
WHERE employee_id = emp_id;
IF commission IS NULL THEN
RAISE comm_missing;
ELSE
UPDATE employees SET salary = salary + bonus*commission
WHERE employee_id = emp_id;
END IF;
EXCEPTION -- exception-handling part starts here
WHEN comm_missing THEN
DBMS_OUTPUT.PUT_LINE('This employee does not receive a commission.');
commission := 0;
WHEN OTHERS THEN
NULL; -- for other exceptions do nothing
END award_bonus;
/
CALL award_bonus(150, 400);
When called, this procedure accepts an employee Id and a bonus amount. It uses the Id to select the employee's commission percentage from a database table and, at the same time, convert the commission percentage to a decimal amount. Then, it checks the commission amount.
If the commission is null, an exception is raised; otherwise, the employee's salary is updated.