SlideShare a Scribd company logo
1 of 198
Copyright © 2007, Oracle. All rights reserved.
Introduction to PL/SQL
Copyright © 2007, Oracle. All rights reserved.
1 - 2
Objectives
After completing this lesson, you should be able to do the
following:
• Explain the need for PL/SQL
• Explain the benefits of PL/SQL
• Identify the different types of PL/SQL blocks
• Output messages in PL/SQL
Copyright © 2007, Oracle. All rights reserved.
1 - 3
About PL/SQL
PL/SQL:
• Stands for “Procedural Language extension to SQL”
• Is Oracle Corporation’s standard data access language for
relational databases
• Seamlessly integrates procedural constructs with SQL
Copyright © 2007, Oracle. All rights reserved.
1 - 4
About PL/SQL
PL/SQL:
• Provides a block structure for executable units of code.
Maintenance of code is made easier with such a well-defined
structure.
• Provides procedural constructs such as:
– Variables, constants, and data types
– Control structures such as conditional statements and loops
– Reusable program units that are written once and executed
many times
Copyright © 2007, Oracle. All rights reserved.
1 - 5
PL/SQL Environment
PL/SQL engine
Oracle database server
SQL statement
executor
Procedural
statement
executor
procedural
SQL
PL/SQL
block
Copyright © 2007, Oracle. All rights reserved.
1 - 6
Benefits of PL/SQL
• Integration of procedural constructs with SQL
• Improved performance
SQL
IF...THEN
SQL
ELSE
SQL
END IF;
SQL
SQL 1
SQL 2
…
Copyright © 2007, Oracle. All rights reserved.
1 - 7
Benefits of PL/SQL
• Modularized program development
• Integration with Oracle tools
• Portability
• Exception handling
Copyright © 2007, Oracle. All rights reserved.
1 - 9
PL/SQL Block Structure
• DECLARE (optional)
– Variables, cursors, user-defined exceptions
• BEGIN (mandatory)
– SQL statements
– PL/SQL statements
• EXCEPTION (optional)
– Actions to perform
when errors occur
• END; (mandatory)
Copyright © 2007, Oracle. All rights reserved.
1 - 11
Block Types
Anonymous Procedure Function
[DECLARE]
BEGIN
--statements
[EXCEPTION]
END;
PROCEDURE name
IS
BEGIN
--statements
[EXCEPTION]
END;
FUNCTION name
RETURN datatype
IS
BEGIN
--statements
RETURN value;
[EXCEPTION]
END;
Copyright © 2007, Oracle. All rights reserved.
1 - 13
Program Constructs
Application triggers
Application packages
Application procedures
or functions
Anonymous blocks
Tools Constructs
Object types
Database triggers
Stored packages
Stored procedures or
functions
Anonymous blocks
Database Server
Constructs
Object types
Copyright © 2007, Oracle. All rights reserved.
1 - 15
Create an Anonymous Block
Enter the anonymous block in the SQL Developer workspace:
Copyright © 2007, Oracle. All rights reserved.
1 - 16
Execute an Anonymous Block
Click the Run Script button to execute the anonymous block:
Run Script
Copyright © 2007, Oracle. All rights reserved.
1 - 17
Test the Output of a PL/SQL Block
• Enable output in SQL Developer by clicking the Enable
DBMS Output button on the DBMS Output tab:
• Use a predefined Oracle package and its procedure:
– DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE(' The First Name of the
Employee is ' || f_name);
…
Enable DBMS
Output
DBMS Output
Tab
Copyright © 2007, Oracle. All rights reserved.
1 - 18
Test the Output of a PL/SQL Block
Copyright © 2007, Oracle. All rights reserved.
1 - 19
Summary
In this lesson, you should have learned how to:
• Integrate SQL statements with PL/SQL program constructs
• Describe the benefits of PL/SQL
• Differentiate between PL/SQL block types
• Output messages in PL/SQL
Copyright © 2007, Oracle. All rights reserved.
1 - 20
Practice 1: Overview
This practice covers the following topics:
• Identifying the PL/SQL blocks that execute successfully
• Creating and executing a simple PL/SQL block
Copyright © 2007, Oracle. All rights reserved.
Declaring PL/SQL Variables
Copyright © 2007, Oracle. All rights reserved.
2 - 23
Objectives
After completing this lesson, you should be able to do the
following:
• Recognize valid and invalid identifiers
• List the uses of variables
• Declare and initialize variables
• List and describe various data types
• Identify the benefits of using the %TYPE attribute
• Declare, use, and print bind variables
Copyright © 2007, Oracle. All rights reserved.
2 - 24
Use of Variables
Variables can be used for:
• Temporary storage of data
• Manipulation of stored values
• Reusability
SELECT
first_name,
department_id
INTO
v_fname,
v_deptno
FROM …
v_fname
v_deptno
Jennifer
10
Copyright © 2007, Oracle. All rights reserved.
2 - 25
Requirements for Variable Names
A variable name:
• Must start with a letter
• Can include letters or numbers
• Can include special characters (such as $, _, and # )
• Must contain no more than 30 characters
• Must not include reserved words
Copyright © 2007, Oracle. All rights reserved.
2 - 26
Handling Variables in PL/SQL
Variables are:
• Declared and initialized in the declarative section
• Used and assigned new values in the executable section
• Passed as parameters to PL/SQL subprograms
• Used to hold the output of a PL/SQL subprogram
Copyright © 2007, Oracle. All rights reserved.
2 - 27
Declaring and Initializing PL/SQL Variables
Syntax:
Examples:
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
DECLARE
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := 'Atlanta';
c_comm CONSTANT NUMBER := 1400;
Copyright © 2007, Oracle. All rights reserved.
2 - 28
Declaring and Initializing PL/SQL Variables
DECLARE
v_myName VARCHAR2(20);
BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
v_myName := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
DECLARE
v_myName VARCHAR2(20):= 'John';
BEGIN
v_myName := 'Steven';
DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName);
END;
/
1
2
Copyright © 2007, Oracle. All rights reserved.
2 - 29
Delimiters in String Literals
DECLARE
v_event VARCHAR2(15);
BEGIN
v_event := q'!Father's day!';
DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is :
'|| v_event );
v_event := q'[Mother's day]';
DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is :
'|| v_event );
END;
/
Copyright © 2007, Oracle. All rights reserved.
2 - 30
Types of Variables
• PL/SQL variables:
– Scalar
– Composite
– Reference
– Large object (LOB)
• Non-PL/SQL variables: Bind variables
Copyright © 2007, Oracle. All rights reserved.
2 - 31
TRUE
Types of Variables
25-JAN-01
Atlanta
256120.08
Snow White
Long, long ago,
in a land far, far away,
there lived a princess called
Snow White. . .
Copyright © 2007, Oracle. All rights reserved.
2 - 32
Guidelines for Declaring and Initializing
PL/SQL Variables
• Follow naming conventions.
• Use meaningful identifiers for variables.
• Initialize variables designated as NOT NULL and
CONSTANT.
• Initialize variables with the assignment operator (:=) or
the DEFAULT keyword:
• Declare one identifier per line for better readability and
code maintenance.
v_myName VARCHAR2(20):='John';
v_myName VARCHAR2(20) DEFAULT 'John';
Copyright © 2007, Oracle. All rights reserved.
2 - 33
Guidelines for Declaring PL/SQL Variables
• Avoid using column names as identifiers.
• Use the NOT NULL constraint when the variable must
hold a value.
DECLARE
employee_id NUMBER(6);
BEGIN
SELECT employee_id
INTO employee_id
FROM employees
WHERE last_name = 'Kochhar';
END;
/
Copyright © 2007, Oracle. All rights reserved.
2 - 34
Scalar Data Types
• Hold a single value
• Have no internal components
Atlanta
TRUE 25-JAN-01
256120.08
The soul of the lazy man
desires, and he has nothing;
but the soul of the diligent
shall be made rich.
Copyright © 2007, Oracle. All rights reserved.
2 - 35
Base Scalar Data Types
• CHAR [(maximum_length)]
• VARCHAR2 (maximum_length)
• NUMBER [(precision, scale)]
• BINARY_INTEGER
• PLS_INTEGER
• BOOLEAN
• BINARY_FLOAT
• BINARY_DOUBLE
Copyright © 2007, Oracle. All rights reserved.
2 - 37
Base Scalar Data Types
• DATE
• TIMESTAMP
• TIMESTAMP WITH TIME ZONE
• TIMESTAMP WITH LOCAL TIME ZONE
• INTERVAL YEAR TO MONTH
• INTERVAL DAY TO SECOND
Copyright © 2007, Oracle. All rights reserved.
2 - 39
Declaring Scalar Variables
Examples:
DECLARE
v_emp_job VARCHAR2(9);
v_count_loop BINARY_INTEGER := 0;
v_dept_total_sal NUMBER(9,2) := 0;
v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
...
Copyright © 2007, Oracle. All rights reserved.
2 - 40
%TYPE Attribute
• Is used to declare a variable according to:
– A database column definition
– Another declared variable
• Is prefixed with:
– The database table and column
– The name of the declared variable
Copyright © 2007, Oracle. All rights reserved.
2 - 42
Declaring Variables
with the %TYPE Attribute
Syntax
Examples
...
emp_lname employees.last_name%TYPE;
...
identifier table.column_name%TYPE;
...
balance NUMBER(7,2);
min_balance balance%TYPE := 1000;
...
Copyright © 2007, Oracle. All rights reserved.
2 - 43
Declaring Boolean Variables
• Only the TRUE, FALSE, and NULL values can be assigned
to a Boolean variable.
• Conditional expressions use the logical operators AND
and OR and the unary operator NOT to check the variable
values.
• The variables always yield TRUE, FALSE, or NULL.
• Arithmetic, character, and date expressions can be used
to return a Boolean value.
Copyright © 2007, Oracle. All rights reserved.
2 - 44
Bind Variables
Bind variables are:
• Created in the environment
• Also called host variables
• Created with the VARIABLE keyword
• Used in SQL statements and PL/SQL blocks
• Accessed even after the PL/SQL block is executed
• Referenced with a preceding colon
Copyright © 2007, Oracle. All rights reserved.
2 - 46
Printing Bind Variables
Example:
VARIABLE b_emp_salary NUMBER
BEGIN
SELECT salary INTO :b_emp_salary
FROM employees WHERE employee_id = 178;
END;
/
PRINT b_emp_salary
SELECT first_name, last_name FROM employees
WHERE salary=:b_emp_salary;
Copyright © 2007, Oracle. All rights reserved.
2 - 47
Printing Bind Variables
Example:
VARIABLE b_emp_salary NUMBER
SET AUTOPRINT ON
DECLARE
v_empno NUMBER(6):=&empno;
BEGIN
SELECT salary INTO :b_emp_salary
FROM employees WHERE employee_id = v_empno;
END;
7000
Output:
Copyright © 2007, Oracle. All rights reserved.
2 - 48
LOB Data Type Variables
Book
(CLOB)
Photo
(BLOB)
Movie
(BFILE)
NCLOB
Copyright © 2007, Oracle. All rights reserved.
2 - 49
Composite Data Types
TRUE 23-DEC-98 ATLANTA
1 5000
2 2345
3 12
4 3456
1 SMITH
2 JONES
3 NANCY
4 TIM
PL/SQL table structure PL/SQL table structure
PLS_INTEGER
VARCHAR2
PLS_INTEGER
NUMBER
Copyright © 2007, Oracle. All rights reserved.
2 - 50
Summary
In this lesson, you should have learned how to:
• Recognize valid and invalid identifiers
• Declare variables in the declarative section of a PL/SQL
block
• Initialize variables and use them in the executable section
• Differentiate between scalar and composite data types
• Use the %TYPE attribute
• Use bind variables
Copyright © 2007, Oracle. All rights reserved.
2 - 51
Practice 2: Overview
This practice covers the following topics:
• Determining valid identifiers
• Determining valid variable declarations
• Declaring variables within an anonymous block
• Using the %TYPE attribute to declare variables
• Declaring and printing a bind variable
• Executing a PL/SQL block
Copyright © 2007, Oracle. All rights reserved.
Writing Executable Statements
Copyright © 2007, Oracle. All rights reserved.
3 - 55
Objectives
After completing this lesson, you should be able to do the
following:
• Identify lexical units in a PL/SQL block
• Use built-in SQL functions in PL/SQL
• Describe when implicit conversions take place and when
explicit conversions have to be dealt with
• Write nested blocks and qualify variables with labels
• Write readable code with appropriate indentation
• Use sequences in PL/SQL expressions
Copyright © 2007, Oracle. All rights reserved.
3 - 56
Lexical Units in a PL/SQL Block
Lexical units:
• Are building blocks of any PL/SQL block
• Are sequences of characters including letters, numerals,
tabs, spaces, returns, and symbols
• Can be classified as:
– Identifiers: v_fname, c_percent
– Delimiters: ; , +, -
– Literals: John, 428, True
– Comments: --, /* */
Copyright © 2007, Oracle. All rights reserved.
3 - 58
PL/SQL Block Syntax and Guidelines
• Literals
– Character and date literals must be enclosed in single
quotation marks.
– Numbers can be simple values or in scientific notation.
• Statements can span several lines.
name := 'Henderson';
1
2
3
Copyright © 2007, Oracle. All rights reserved.
3 - 59
Commenting Code
• Prefix single-line comments with two hyphens (--).
• Place multiple-line comments between the symbols /*
and */.
Example:
DECLARE
...
v_annual_sal NUMBER (9,2);
BEGIN
/* Compute the annual salary based on the
monthly salary input from the user */
v_annual_sal := monthly_sal * 12;
--The following line displays the annual salary
DBMS_OUTPUT.PUT_LINE(v_annual_sal);
END;
/
Copyright © 2007, Oracle. All rights reserved.
3 - 60
SQL Functions in PL/SQL
• Available in procedural statements:
– Single-row functions
• Not available in procedural statements:
– DECODE
– Group functions
Copyright © 2007, Oracle. All rights reserved.
3 - 61
SQL Functions in PL/SQL: Examples
• Get the length of a string:
• Get the number of months an employee has worked:
v_desc_size INTEGER(5);
v_prod_description VARCHAR2(70):='You can use this
product with your radios for higher frequency';
-- get the length of the string in prod_description
v_desc_size:= LENGTH(prod_description);
v_tenure:= MONTHS_BETWEEN (CURRENT_DATE, v_hiredate);
Copyright © 2007, Oracle. All rights reserved.
3 - 62
Using Sequences in PL/SQL Expressions
Starting in 11g:
Before 11g:
DECLARE
v_new_id NUMBER;
BEGIN
SELECT my_seq.NEXTVAL INTO v_new_id FROM Dual;
END;
/
DECLARE
v_new_id NUMBER;
BEGIN
v_new_id := my_seq.NEXTVAL;
END;
/
Copyright © 2007, Oracle. All rights reserved.
3 - 63
Data Type Conversion
• Converts data to comparable data types
• Is of two types:
– Implicit conversion
– Explicit conversion
• Functions:
– TO_CHAR
– TO_DATE
– TO_NUMBER
– TO_TIMESTAMP
Copyright © 2007, Oracle. All rights reserved.
3 - 65
Data Type Conversion
date_of_joining DATE:= '02-Feb-2000';
date_of_joining DATE:= 'February 02,2000';
date_of_joining DATE:= TO_DATE('February
02,2000','Month DD, YYYY');
1
2
3
Copyright © 2007, Oracle. All rights reserved.
3 - 66
Nested Blocks
PL/SQL blocks can be nested.
• An executable section (BEGIN … END)
can contain nested blocks.
• An exception section can contain
nested blocks.
Copyright © 2007, Oracle. All rights reserved.
3 - 67
Nested Blocks
Example:
DECLARE
v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE';
BEGIN
DECLARE
v_inner_variable VARCHAR2(20):='LOCAL VARIABLE';
BEGIN
DBMS_OUTPUT.PUT_LINE(v_inner_variable);
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
DBMS_OUTPUT.PUT_LINE(v_outer_variable);
END;
Copyright © 2007, Oracle. All rights reserved.
3 - 68
Variable Scope and Visibility
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name);
END;
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
/
1
2
Copyright © 2007, Oracle. All rights reserved.
3 - 70
Qualify an Identifier
BEGIN <<outer>>
DECLARE
v_father_name VARCHAR2(20):='Patrick';
v_date_of_birth DATE:='20-Apr-1972';
BEGIN
DECLARE
v_child_name VARCHAR2(20):='Mike';
v_date_of_birth DATE:='12-Dec-2002';
BEGIN
DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '
||outer.v_date_of_birth);
DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name);
DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth);
END;
END;
END outer;
Copyright © 2007, Oracle. All rights reserved.
3 - 71
Quiz: Determining Variable Scope
BEGIN <<outer>>
DECLARE
v_sal NUMBER(7,2) := 60000;
v_comm NUMBER(7,2) := v_sal * 0.20;
v_message VARCHAR2(255) := ' eligible for commission';
BEGIN
DECLARE
v_sal NUMBER(7,2) := 50000;
v_comm NUMBER(7,2) := 0;
v_total_comp NUMBER(7,2) := v_sal + v_comm;
BEGIN
v_message := 'CLERK not'||v_message;
outer.v_comm := v_sal * 0.30;
END;
v_message := 'SALESMAN'||v_message;
END;
END outer;
/
1
2
Copyright © 2007, Oracle. All rights reserved.
3 - 73
Operators in PL/SQL
• Logical
• Arithmetic
• Concatenation
• Parentheses to control order
of operations
• Exponential operator (**)
Same as in SQL
}
Copyright © 2007, Oracle. All rights reserved.
3 - 74
Operators in PL/SQL: Examples
• Increment the counter for a loop.
• Set the value of a Boolean flag.
• Validate whether an employee number contains a value.
loop_count := loop_count + 1;
good_sal := sal BETWEEN 50000 AND 150000;
valid := (empno IS NOT NULL);
Copyright © 2007, Oracle. All rights reserved.
3 - 75
Programming Guidelines
Make code maintenance easier by:
• Documenting code with comments
• Developing a case convention for the code
• Developing naming conventions for identifiers and other
objects
• Enhancing readability by indenting
Copyright © 2007, Oracle. All rights reserved.
3 - 76
Indenting Code
For clarity, indent each level of code.
BEGIN
IF x=0 THEN
y:=1;
END IF;
END;
/
DECLARE
deptno NUMBER(4);
location_id NUMBER(4);
BEGIN
SELECT department_id,
location_id
INTO deptno,
location_id
FROM departments
WHERE department_name
= 'Sales';
...
END;
/
Copyright © 2007, Oracle. All rights reserved.
3 - 77
Summary
In this lesson, you should have learned how to:
• Identify lexical units in a PL/SQL block
• Use built-in SQL functions in PL/SQL
• Write nested blocks to break logically related
functionalities
• Decide when to perform explicit conversions
• Qualify variables in nested blocks
• Use sequences in PL/SQL expressions
Copyright © 2007, Oracle. All rights reserved.
3 - 78
Practice 3: Overview
This practice covers the following topics:
• Reviewing scoping and nesting rules
• Writing and testing PL/SQL blocks
Copyright © 2007, Oracle. All rights reserved.
Interacting with the Oracle Database Server
Copyright © 2007, Oracle. All rights reserved.
4 - 83
Objectives
After completing this lesson, you should be able to do the
following:
• Determine the SQL statements that can be directly
included in a PL/SQL executable block
• Manipulate data with DML statements in PL/SQL
• Use transaction control statements in PL/SQL
• Make use of the INTO clause to hold the values returned
by a SQL statement
• Differentiate between implicit cursors and explicit cursors
• Use SQL cursor attributes
Copyright © 2007, Oracle. All rights reserved.
4 - 84
SQL Statements in PL/SQL
• Retrieve a row from the database by using the SELECT
command.
• Make changes to rows in the database by using DML
commands.
• Control a transaction with the COMMIT, ROLLBACK, or
SAVEPOINT command.
Copyright © 2007, Oracle. All rights reserved.
4 - 85
SELECT Statements in PL/SQL
Retrieve data from the database with a SELECT statement.
Syntax:
SELECT select_list
INTO {variable_name[, variable_name]...
| record_name}
FROM table
[WHERE condition];
Copyright © 2007, Oracle. All rights reserved.
4 - 87
SELECT Statements in PL/SQL
• The INTO clause is required.
• Queries must return only one row.
Example:
DECLARE
v_fname VARCHAR2(25);
BEGIN
SELECT first_name INTO v_fname
FROM employees WHERE employee_id=200;
DBMS_OUTPUT.PUT_LINE(' First Name is : '||v_fname);
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 89
Retrieving Data in PL/SQL
Retrieve hire_date and salary for the specified
employee.
Example:
DECLARE
v_emp_hiredate employees.hire_date%TYPE;
v_emp_salary employees.salary%TYPE;
BEGIN
SELECT hire_date, salary
INTO v_emp_hiredate, v_emp_salary
FROM employees
WHERE employee_id = 100;
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 90
DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 60;
BEGIN
SELECT SUM(salary) -- group function
INTO v_sum_sal FROM employees
WHERE department_id = v_deptno;
DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal);
END;
Retrieving Data in PL/SQL
Return the sum of the salaries for all the employees in the
specified department.
Example:
Copyright © 2007, Oracle. All rights reserved.
4 - 91
Naming Conventions
DECLARE
hire_date employees.hire_date%TYPE;
sysdate hire_date%TYPE;
employee_id employees.employee_id%TYPE := 176;
BEGIN
SELECT hire_date, sysdate
INTO hire_date, sysdate
FROM employees
WHERE employee_id = employee_id;
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 92
Naming Conventions
• Use a naming convention to avoid ambiguity in the
WHERE clause.
• Avoid using database column names as identifiers.
• Syntax errors can arise because PL/SQL checks the
database first for a column in the table.
• The names of local variables and formal parameters take
precedence over the names of database tables.
• The names of database table columns take precedence
over the names of local variables.
Copyright © 2007, Oracle. All rights reserved.
4 - 93
Using PL/SQL to Manipulate Data
Make changes to database tables by using DML commands:
• INSERT
• UPDATE
• DELETE
• MERGE
INSERT
UPDATE
DELETE
MERGE
Copyright © 2007, Oracle. All rights reserved.
4 - 94
Inserting Data
Add new employee information to the EMPLOYEES table.
Example:
BEGIN
INSERT INTO employees
(employee_id, first_name, last_name, email,
hire_date, job_id, salary)
VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores',
'RCORES',CURRENT_DATE, 'AD_ASST', 4000);
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 95
Updating Data
Increase the salary of all employees who are stock clerks.
Example:
DECLARE
sal_increase employees.salary%TYPE := 800;
BEGIN
UPDATE employees
SET salary = salary + sal_increase
WHERE job_id = 'ST_CLERK';
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 96
Deleting Data
Delete rows that belong to department 10 from the
employees table.
Example:
DECLARE
deptno employees.department_id%TYPE := 10;
BEGIN
DELETE FROM employees
WHERE department_id = deptno;
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 97
Merging Rows
Insert or update rows in the copy_emp table to match the
employees table.
BEGIN
MERGE INTO copy_emp c
USING employees e
ON (e.employee_id = c.empno)
WHEN MATCHED THEN
UPDATE SET
c.first_name = e.first_name,
c.last_name = e.last_name,
c.email = e.email,
. . .
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name, e.last_name,
. . .,e.department_id);
END;
/
Copyright © 2007, Oracle. All rights reserved.
4 - 99
SQL Cursor
• A cursor is a pointer to the private memory area
allocated by the Oracle server.
• A cursor is used to handle the result set of a SELECT
statement.
• There are two types of cursors:
– Implicit: Created and managed internally by the Oracle
server to process SQL statements
– Explicit: Declared explicitly by the programmer
Copyright © 2007, Oracle. All rights reserved.
4 - 101
SQL Cursor Attributes for Implicit Cursors
Using SQL cursor attributes, you can test the outcome of
your SQL statements.
SQL%FOUND Boolean attribute that evaluates to TRUE if the
most recent SQL statement returned at least
one row
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if
the most recent SQL statement did not
return even one row
SQL%ROWCOUNT An integer value that represents the number of
rows affected by the most recent SQL
statement
Copyright © 2007, Oracle. All rights reserved.
4 - 102
SQL Cursor Attributes for Implicit Cursors
Delete rows that have the specified employee ID from the
employees table. Print the number of rows deleted.
Example:
DECLARE
v_rows_deleted VARCHAR2(30)
v_empno employees.employee_id%TYPE := 176;
BEGIN
DELETE FROM employees
WHERE employee_id = v_empno;
v_rows_deleted := (SQL%ROWCOUNT ||
' row deleted.');
DBMS_OUTPUT.PUT_LINE (v_rows_deleted);
END;
Copyright © 2007, Oracle. All rights reserved.
4 - 103
Summary
In this lesson, you should have learned how to:
• Embed DML statements, transaction control statements,
and DDL statements in PL/SQL
• Use the INTO clause, which is mandatory for all SELECT
statements in PL/SQL
• Differentiate between implicit cursors and explicit cursors
• Use SQL cursor attributes to determine the outcome of
SQL statements
Copyright © 2007, Oracle. All rights reserved.
4 - 104
Practice 4: Overview
This practice covers the following topics:
• Selecting data from a table
• Inserting data into a table
• Updating data in a table
• Deleting a record from a table
Copyright © 2007, Oracle. All rights reserved.
Writing Control Structures
Copyright © 2007, Oracle. All rights reserved.
5 - 108
Objectives
After completing this lesson, you should be able to do the
following:
• Identify the uses and types of control structures
• Construct an IF statement
• Use CASE statements and CASE expressions
• Construct and identify loop statements
• Use guidelines when using conditional control structures
Copyright © 2007, Oracle. All rights reserved.
5 - 109
Controlling Flow of Execution
for
loop
while
Copyright © 2007, Oracle. All rights reserved.
5 - 110
IF Statement
Syntax:
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
Copyright © 2007, Oracle. All rights reserved.
5 - 112
Simple IF Statement
DECLARE
v_myage number:=31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
END IF;
END;
/
Output:
Copyright © 2007, Oracle. All rights reserved.
5 - 113
IF THEN ELSE Statement
DECLARE
v_myage number:=31;
BEGIN
IF v_myage < 11
THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
ELSE
DBMS_OUTPUT.PUT_LINE(' I am not a child ');
END IF;
END;
/
Output:
Copyright © 2007, Oracle. All rights reserved.
5 - 114
IF ELSIF ELSE Clause
DECLARE
v_myage number:=31;
BEGIN
IF v_myage < 11 THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
ELSIF v_myage < 20 THEN
DBMS_OUTPUT.PUT_LINE(' I am young ');
ELSIF v_myage < 30 THEN
DBMS_OUTPUT.PUT_LINE(' I am in my twenties');
ELSIF v_myage < 40 THEN
DBMS_OUTPUT.PUT_LINE(' I am in my thirties');
ELSE
DBMS_OUTPUT.PUT_LINE(' I am always young ');
END IF;
END;
/
Output:
Copyright © 2007, Oracle. All rights reserved.
5 - 115
NULL Value in IF Statement
DECLARE
v_myage number;
BEGIN
IF v_myage < 11 THEN
DBMS_OUTPUT.PUT_LINE(' I am a child ');
ELSE
DBMS_OUTPUT.PUT_LINE(' I am not a child ');
END IF;
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 116
CASE Expressions
• A CASE expression selects a result and returns it.
• To select the result, the CASE expression uses
expressions. The value returned by these expressions is
used to select one of several alternatives.
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE resultN+1]
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 117
CASE Expressions: Example
SET VERIFY OFF
DECLARE
v_grade CHAR(1) := UPPER('&grade');
appraisal VARCHAR2(20);
BEGIN
appraisal := CASE v_grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
ELSE 'No such grade'
END;
DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || '
Appraisal ' || appraisal);
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 118
Searched CASE Expressions
DECLARE
v_grade CHAR(1) := UPPER('&grade');
appraisal VARCHAR2(20);
BEGIN
appraisal := CASE
WHEN v_grade = 'A' THEN 'Excellent'
WHEN v_grade IN ('B','C') THEN 'Good'
ELSE 'No such grade'
END;
DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || '
Appraisal ' || appraisal);
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 119
CASE Statement
DECLARE
v_deptid NUMBER;
v_deptname VARCHAR2(20);
v_emps NUMBER;
v_mngid NUMBER:= 108;
BEGIN
CASE v_mngid
WHEN 108 THEN
SELECT department_id, department_name
INTO v_deptid, v_deptname FROM departments
WHERE manager_id=108;
SELECT count(*) INTO v_emps FROM employees
WHERE department_id=v_deptid;
WHEN 200 THEN
...
END CASE;
DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname||
' department. There are '||v_emps ||' employees in this
department');
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 120
Handling Nulls
When working with nulls, you can avoid some common
mistakes by keeping in mind the following rules:
• Simple comparisons involving nulls always yield NULL.
• Applying the logical operator NOT to a null yields NULL.
• If the condition yields NULL in conditional control
statements, its associated sequence of statements is not
executed.
Copyright © 2007, Oracle. All rights reserved.
5 - 121
Logic Tables
Build a simple Boolean condition with a comparison
operator.
AND
TRUE
FALSE
NULL
TRUE FALSE NULL
TRUE
NULL NULL
NULL
FALSE FALSE
FALSE
FALSE
FALSE
NOT
TRUE
FALSE
NULL
FALSE
TRUE
NULL
TRUE
NULL
OR TRUE FALSE NULL
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
NULL NULL
NULL
FALSE
Copyright © 2007, Oracle. All rights reserved.
5 - 122
Boolean Conditions
What is the value of flag in each case?
REORDER_FLAG AVAILABLE_FLAG FLAG
TRUE TRUE
TRUE FALSE
NULL TRUE
NULL FALSE
flag := reorder_flag AND available_flag;
? (1)
? (2)
? (3)
? (4)
Copyright © 2007, Oracle. All rights reserved.
5 - 123
Iterative Control: LOOP Statements
• Loops repeat a statement (or sequence of statements)
multiple times.
• There are three loop types:
– Basic loop
– FOR loop
– WHILE loop
Copyright © 2007, Oracle. All rights reserved.
5 - 124
Basic Loops
Syntax:
LOOP
statement1;
. . .
EXIT [WHEN condition];
END LOOP;
Copyright © 2007, Oracle. All rights reserved.
5 - 125
DECLARE
v_countryid locations.country_id%TYPE := 'CA';
v_loc_id locations.location_id%TYPE;
v_counter NUMBER(2) := 1;
v_new_city locations.city%TYPE := 'Montreal';
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = v_countryid;
LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), v_new_city, v_countryid);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 3;
END LOOP;
END;
/
Basic Loops
Example:
Copyright © 2007, Oracle. All rights reserved.
5 - 126
WHILE Loops
Syntax:
Use the WHILE loop to repeat statements while a condition
is TRUE.
WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;
Copyright © 2007, Oracle. All rights reserved.
5 - 127
WHILE Loops
Example
DECLARE
v_countryid locations.country_id%TYPE := 'CA';
v_loc_id locations.location_id%TYPE;
v_new_city locations.city%TYPE := 'Montreal';
v_counter NUMBER := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations
WHERE country_id = v_countryid;
WHILE v_counter <= 3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), v_new_city, v_countryid);
v_counter := v_counter + 1;
END LOOP;
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 128
FOR Loops
• Use a FOR loop to shortcut the test for the number of
iterations.
• Do not declare the counter; it is declared implicitly.
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
Copyright © 2007, Oracle. All rights reserved.
5 - 130
FOR Loops
Example:
DECLARE
v_countryid locations.country_id%TYPE := 'CA';
v_loc_id locations.location_id%TYPE;
v_new_city locations.city%TYPE := 'Montreal';
BEGIN
SELECT MAX(location_id) INTO v_loc_id
FROM locations
WHERE country_id = v_countryid;
FOR i IN 1..3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + i), v_new_city, v_countryid );
END LOOP;
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 131
FOR Loops
Guidelines
• Reference the counter within the loop only; it is
undefined outside the loop.
• Do not reference the counter as the target of an
assignment.
• Neither loop bound should be NULL.
Copyright © 2007, Oracle. All rights reserved.
5 - 132
Guidelines for Loops
• Use the basic loop when the statements inside the loop
must execute at least once.
• Use the WHILE loop if the condition must be evaluated at
the start of each iteration.
• Use a FOR loop if the number of iterations is known.
Copyright © 2007, Oracle. All rights reserved.
5 - 133
Nested Loops and Labels
• You can nest loops to multiple levels.
• Use labels to distinguish between blocks and loops.
• Exit the outer loop with the EXIT statement that
references the label.
Copyright © 2007, Oracle. All rights reserved.
5 - 134
Nested Loops and Labels
...
BEGIN
<<Outer_loop>>
LOOP
v_counter := v_counter+1;
EXIT WHEN v_counter>10;
<<Inner_loop>>
LOOP
...
EXIT Outer_loop WHEN total_done = 'YES';
-- Leave both loops
EXIT WHEN inner_done = 'YES';
-- Leave inner loop only
...
END LOOP Inner_loop;
...
END LOOP Outer_loop;
END;
/
Copyright © 2007, Oracle. All rights reserved.
5 - 135
PL/SQL CONTINUE Statement
• Definition
– Adds the functionality to begin the next loop iteration
– Provides programmers with the ability to transfer control
to the next iteration of a loop
– Uses parallel structure and semantics to the EXIT
statement
• Benefits
– Eases the programming process
– May see a small performance improvement over the
previous programming workarounds to simulate the
CONTINUE statement
Copyright © 2007, Oracle. All rights reserved.
5 - 136
PL/SQL CONTINUE Statement: Example
DECLARE
v_total SIMPLE_INTEGER := 0;
BEGIN
FOR i IN 1..10 LOOP
v_total := v_total + i;
dbms_output.put_line
('Total is: '|| v_total);
CONTINUE WHEN i > 5;
v_total := v_total + i;
dbms_output.put_line
('Out of Loop Total is:
'|| v_total);
END LOOP;
END;
/
1
2
anonymous block completed
Total is: 1
Out of Loop Total is: 2
Total is: 4
Out of Loop Total is: 6
Total is: 9
Out of Loop Total is: 12
Total is: 16
Out of Loop Total is: 20
Total is: 25
Out of Loop Total is: 30
Total is: 36
Total is: 43
Total is: 51
Total is: 60
Total is: 70
Copyright © 2007, Oracle. All rights reserved.
5 - 137
PL/SQL CONTINUE Statement: Example
DECLARE
v_total NUMBER := 0;
BEGIN
<<BeforeTopLoop>>
FOR i IN 1..10 LOOP
v_total := v_total + 1;
dbms_output.put_line
('Total is: ' || v_total);
FOR j IN 1..10 LOOP
CONTINUE BeforeTopLoop WHEN i + j > 5;
v_total := v_total + 1;
END LOOP;
END LOOP;
END two_loop;
anonymous block completed
Total is: 1
Total is: 6
Total is: 10
Total is: 13
Total is: 15
Total is: 16
Total is: 17
Total is: 18
Total is: 19
Total is: 20
Copyright © 2007, Oracle. All rights reserved.
5 - 138
Summary
In this lesson, you should have learned how to change the
logical flow of statements by using the following control
structures:
• Conditional (IF statement)
• CASE expressions and CASE statements
• Loops:
– Basic loop
– FOR loop
– WHILE loop
• EXIT statement
• CONTINUE statement
Copyright © 2007, Oracle. All rights reserved.
5 - 139
Practice 5: Overview
This practice covers the following topics:
• Performing conditional actions by using IF statements
• Performing iterative steps by using LOOP structures
Copyright © 2007, Oracle. All rights reserved.
Working with
Composite Data Types
Copyright © 2007, Oracle. All rights reserved.
6 - 143
Objectives
After completing this lesson, you should be able to do the
following:
• Create user-defined PL/SQL records
• Create a record with the %ROWTYPE attribute
• Create an INDEX BY table
• Create an INDEX BY table of records
• Describe the differences among records, tables, and
tables of records
Copyright © 2007, Oracle. All rights reserved.
6 - 144
Composite Data Types
• Can hold multiple values (unlike scalar types)
• Are of two types:
– PL/SQL records
– PL/SQL collections
— INDEX BY tables or associative arrays
— Nested table
— VARRAY
Copyright © 2007, Oracle. All rights reserved.
6 - 145
Composite Data Types
• Use PL/SQL records when you want to store values of
different data types but only one occurrence at a time.
• Use PL/SQL collections when you want to store values of
the same data type.
Copyright © 2007, Oracle. All rights reserved.
6 - 146
PL/SQL Records
• Must contain one or more components (called fields) of
any scalar, RECORD, or INDEX BY table data type
• Are similar to structures in most third-generation
languages (including C and C++)
• Are user defined and can be a subset of a row in a table
• Treat a collection of fields as a logical unit
• Are convenient for fetching a row of data from a table for
processing
Copyright © 2007, Oracle. All rights reserved.
6 - 147
Creating a PL/SQL Record
Syntax:
TYPE type_name IS RECORD
(field_declaration[, field_declaration]…);
field_name {field_type | variable%TYPE
| table.column%TYPE | table%ROWTYPE}
[[NOT NULL] {:= | DEFAULT} expr]
identifier type_name;
1
2
field_declaration:
Copyright © 2007, Oracle. All rights reserved.
6 - 148
Creating a PL/SQL Record
Declare variables to store the name, job, and salary of a
new employee.
Example:
DECLARE
type t_rec is record
(v_sal number(8),
v_minsal number(8) default 1000,
v_hire_date employees.hire_date%type,
v_rec1 employees%rowtype);
v_myrec t_rec;
BEGIN
v_myrec.v_sal := v_myrec.v_minsal + 500;
v_myrec.v_hire_date := sysdate;
SELECT * INTO v_myrec.v_rec1
FROM employees WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE(v_myrec.v_rec1.last_name ||' '||
to_char(v_myrec.v_hire_date) ||' '|| to_char(v_myrec.v_sal));
END;
Copyright © 2007, Oracle. All rights reserved.
6 - 149
PL/SQL Record Structure
Example:
100 King AD_PRES
employee_id number(6) last_name varchar2(25) job_id varchar2(10)
Field2 (data type) Field3 (data type)
Field1 (data type)
Field2 (data type) Field3 (data type)
Field1 (data type)
Copyright © 2007, Oracle. All rights reserved.
6 - 150
%ROWTYPE Attribute
• Declare a variable according to a collection of columns
in a database table or view.
• Prefix %ROWTYPE with the database table or view.
• Fields in the record take their names and data types from
the columns of the table or view.
Syntax:
DECLARE
identifier reference%ROWTYPE;
Copyright © 2007, Oracle. All rights reserved.
6 - 152
Advantages of Using %ROWTYPE
• The number and data types of the underlying database
columns need not be known—and, in fact, might change
at run time.
• The %ROWTYPE attribute is useful when retrieving a row
with the SELECT * statement.
Copyright © 2007, Oracle. All rights reserved.
6 - 153
%ROWTYPE Attribute: Example
DECLARE
v_employee_number number:= 124;
v_emp_rec employees%ROWTYPE;
BEGIN
SELECT * INTO v_emp_rec FROM employees
WHERE employee_id = v_employee_number;
INSERT INTO retired_emps(empno, ename, job, mgr,
hiredate, leavedate, sal, comm, deptno)
VALUES (v_emp_rec.employee_id, v_emp_rec.last_name,
v_emp_rec.job_id, v_emp_rec.manager_id,
v_emp_rec.hire_date, SYSDATE,
v_emp_rec.salary, v_emp_rec.commission_pct,
v_emp_rec.department_id);
END;
/
Copyright © 2007, Oracle. All rights reserved.
6 - 154
Inserting a Record
by Using %ROWTYPE
...
DECLARE
v_employee_number number:= 124;
v_emp_rec retired_emps%ROWTYPE;
BEGIN
SELECT employee_id, last_name, job_id, manager_id,
hire_date, hire_date, salary, commission_pct,
department_id INTO v_emp_rec FROM employees
WHERE employee_id = v_employee_number;
INSERT INTO retired_emps VALUES v_emp_rec;
END;
/
SELECT * FROM retired_emps;
Copyright © 2007, Oracle. All rights reserved.
6 - 155
Updating a Row in a Table
by Using a Record
SET VERIFY OFF
DECLARE
v_employee_number number:= 124;
v_emp_rec retired_emps%ROWTYPE;
BEGIN
SELECT * INTO v_emp_rec FROM retired_emps;
v_emp_rec.leavedate:=CURRENT_DATE;
UPDATE retired_emps SET ROW = v_emp_rec WHERE
empno=v_employee_number;
END;
/
SELECT * FROM retired_emps;
Copyright © 2007, Oracle. All rights reserved.
6 - 156
INDEX BY Tables or Associative Arrays
• Are PL/SQL structures with two columns:
– Primary key of integer or string data type
– Column of scalar or record data type
• Are unconstrained in size. However, the size depends on
the values that the key data type can hold.
Copyright © 2007, Oracle. All rights reserved.
6 - 157
Creating an INDEX BY Table
Syntax:
Declare an INDEX BY table to store the last names of
employees:
TYPE type_name IS TABLE OF
{column_type | variable%TYPE
| table.column%TYPE} [NOT NULL]
| table%ROWTYPE
[INDEX BY PLS_INTEGER | BINARY_INTEGER
| VARCHAR2(<size>)];
identifier type_name;
...
TYPE ename_table_type IS TABLE OF
employees.last_name%TYPE
INDEX BY PLS_INTEGER;
...
ename_table ename_table_type;
Copyright © 2007, Oracle. All rights reserved.
6 - 159
INDEX BY Table Structure
Unique key Value
... ...
1 Jones
5 Smith
3 Maduro
... ...
PLS_INTEGER Scalar
Copyright © 2007, Oracle. All rights reserved.
6 - 160
Creating an INDEX BY Table
DECLARE
TYPE ename_table_type IS TABLE OF
employees.last_name%TYPE
INDEX BY PLS_INTEGER;
TYPE hiredate_table_type IS TABLE OF DATE
INDEX BY PLS_INTEGER;
ename_table ename_table_type;
hiredate_table hiredate_table_type;
BEGIN
ename_table(1) := 'CAMERON';
hiredate_table(8) := SYSDATE + 7;
IF ename_table.EXISTS(1) THEN
INSERT INTO ...
...
END;
/
Copyright © 2007, Oracle. All rights reserved.
6 - 161
Using INDEX BY Table Methods
The following methods make INDEX BY tables easier to use:
• EXISTS
• COUNT
• FIRST
• LAST
• PRIOR
• NEXT
• DELETE
Copyright © 2007, Oracle. All rights reserved.
6 - 162
INDEX BY Table of Records
Define an INDEX BY table variable to hold an entire row
from a table.
Example:
DECLARE
TYPE dept_table_type IS TABLE OF
departments%ROWTYPE
INDEX BY VARCHAR2(20);
dept_table dept_table_type;
-- Each element of dept_table is a record
Copyright © 2007, Oracle. All rights reserved.
6 - 164
INDEX BY Table of Records: Example
DECLARE
TYPE emp_table_type IS TABLE OF
employees%ROWTYPE INDEX BY PLS_INTEGER;
my_emp_table emp_table_type;
max_count NUMBER(3):= 104;
BEGIN
FOR i IN 100..max_count
LOOP
SELECT * INTO my_emp_table(i) FROM employees
WHERE employee_id = i;
END LOOP;
FOR i IN my_emp_table.FIRST..my_emp_table.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name);
END LOOP;
END;
/
Copyright © 2007, Oracle. All rights reserved.
6 - 165
Nested Tables
1
2
3
4
..
2 GB
Bombay
Sydney
Oxford
London
....
Copyright © 2007, Oracle. All rights reserved.
6 - 167
Bombay
Sydney
Oxford
London
....
VARRAY
Tokyo
1
2
3
4
..
10
Copyright © 2007, Oracle. All rights reserved.
6 - 168
Summary
In this lesson, you should have learned how to:
• Define and reference PL/SQL variables of composite
data types
– PL/SQL record
– INDEX BY table
– INDEX BY table of records
• Define a PL/SQL record by using the %ROWTYPE attribute
Copyright © 2007, Oracle. All rights reserved.
6 - 169
Practice 6: Overview
This practice covers the following topics:
• Declaring INDEX BY tables
• Processing data by using INDEX BY tables
• Declaring a PL/SQL record
• Processing data by using a PL/SQL record
Copyright © 2007, Oracle. All rights reserved.
Using Explicit Cursors
Copyright © 2007, Oracle. All rights reserved.
7 - 174
Objectives
After completing this lesson, you should be able to do the
following:
• Distinguish between implicit and explicit cursors
• Discuss the reasons for using explicit cursors
• Declare and control explicit cursors
• Use simple loops and cursor FOR loops to fetch data
• Declare and use cursors with parameters
• Lock rows with the FOR UPDATE clause
• Reference the current row with the WHERE CURRENT OF
clause
Copyright © 2007, Oracle. All rights reserved.
7 - 175
Cursors
Every SQL statement executed by the Oracle server has an
associated individual cursor:
• Implicit cursors: Declared and managed by PL/SQL for
all DML and PL/SQL SELECT statements
• Explicit cursors: Declared and managed by the
programmer
Copyright © 2007, Oracle. All rights reserved.
7 - 176
Explicit Cursor Operations
Active set
Table
100 King AD_PRES
101 Kochhar AD_VP
102 De Haan AD_VP
. . .
. . .
. . .
139 Seo ST_CLERK
140 Patel ST_CLERK
. . .
Copyright © 2007, Oracle. All rights reserved.
7 - 177
Controlling Explicit Cursors
• Load the
current
row into
variables.
FETCH
• Test for
existing
rows.
EMPTY?
• Return to
FETCH if
rows are
found.
No
• Release the
active set.
CLOSE
Yes
• Create a
named
SQL area.
DECLARE
• Identify the
active set.
OPEN
Copyright © 2007, Oracle. All rights reserved.
7 - 178
Controlling Explicit Cursors
Fetch a row.
Close the cursor.
Cursor
pointer
Open the cursor.
1
2
3
Cursor
pointer
Cursor
pointer
Copyright © 2007, Oracle. All rights reserved.
7 - 179
Declaring the Cursor
Syntax:
Examples:
CURSOR cursor_name IS
select_statement;
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
DECLARE
v_locid NUMBER:= 1700;
CURSOR c_dept_cursor IS
SELECT * FROM departments
WHERE location_id = v_locid;
...
Copyright © 2007, Oracle. All rights reserved.
7 - 181
Opening the Cursor
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
...
BEGIN
OPEN c_emp_cursor;
Copyright © 2007, Oracle. All rights reserved.
7 - 182
Fetching Data from the Cursor
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
v_empno employees.employee_id%TYPE;
v_lname employees.last_name%TYPE;
BEGIN
OPEN c_emp_cursor;
FETCH c_emp_cursor INTO v_empno, v_lname;
DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname);
END;
/
Copyright © 2007, Oracle. All rights reserved.
7 - 184
Fetching Data from the Cursor
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
v_empno employees.employee_id%TYPE;
v_lname employees.last_name%TYPE;
BEGIN
OPEN c_emp_cursor;
LOOP
FETCH c_emp_cursor INTO v_empno, v_lname;
EXIT WHEN c_emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname);
END LOOP;
END;
/
Copyright © 2007, Oracle. All rights reserved.
7 - 185
Closing the Cursor
...
LOOP
FETCH c_emp_cursor INTO empno, lname;
EXIT WHEN c_emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname);
END LOOP;
CLOSE c_emp_cursor;
END;
/
Copyright © 2007, Oracle. All rights reserved.
7 - 186
Cursors and Records
Process the rows of the active set by fetching values into a
PL/SQL record.
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
v_emp_record c_emp_cursor%ROWTYPE;
BEGIN
OPEN c_emp_cursor;
LOOP
FETCH c_emp_cursor INTO v_emp_record;
EXIT WHEN c_emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( v_emp_record.employee_id
||' '||v_emp_record.last_name);
END LOOP;
CLOSE c_emp_cursor;
END;
Copyright © 2007, Oracle. All rights reserved.
7 - 187
Cursor FOR Loops
Syntax:
• The cursor FOR loop is a shortcut to process explicit
cursors.
• Implicit open, fetch, exit, and close occur.
• The record is implicitly declared.
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
Copyright © 2007, Oracle. All rights reserved.
7 - 188
Cursor FOR Loops
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
BEGIN
FOR emp_record IN c_emp_cursor
LOOP
DBMS_OUTPUT.PUT_LINE( emp_record.employee_id
||' ' ||emp_record.last_name);
END LOOP;
END;
/
Copyright © 2007, Oracle. All rights reserved.
7 - 189
Explicit Cursor Attributes
Use explicit cursor attributes to obtain status information
about a cursor.
Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor is open
%NOTFOUND Boolean Evaluates to TRUE if the most recent fetch
does not return a row
%FOUND Boolean Evaluates to TRUE if the most recent fetch
returns a row; complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of rows
returned so far
Copyright © 2007, Oracle. All rights reserved.
7 - 190
%ISOPEN Attribute
• Fetch rows only when the cursor is open.
• Use the %ISOPEN cursor attribute before performing a
fetch to test whether the cursor is open.
Example:
IF NOT c_emp_cursor%ISOPEN THEN
OPEN c_emp_cursor;
END IF;
LOOP
FETCH c_emp_cursor...
Copyright © 2007, Oracle. All rights reserved.
7 - 191
%ROWCOUNT and %NOTFOUND: Example
DECLARE
CURSOR c_emp_cursor IS SELECT employee_id,
last_name FROM employees;
v_emp_record c_emp_cursor%ROWTYPE;
BEGIN
OPEN c_emp_cursor;
LOOP
FETCH c_emp_cursor INTO v_emp_record;
EXIT WHEN c_emp_cursor%ROWCOUNT > 10 OR
c_emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( v_emp_record.employee_id
||' '||v_emp_record.last_name);
END LOOP;
CLOSE c_emp_cursor;
END ;
/
Copyright © 2007, Oracle. All rights reserved.
7 - 192
Cursor FOR Loops Using Subqueries
There is no need to declare the cursor.
Example:
BEGIN
FOR emp_record IN (SELECT employee_id, last_name
FROM employees WHERE department_id =30)
LOOP
DBMS_OUTPUT.PUT_LINE( emp_record.employee_id
||' '||emp_record.last_name);
END LOOP;
END;
/
Copyright © 2007, Oracle. All rights reserved.
7 - 193
Cursors with Parameters
Syntax:
• Pass parameter values to a cursor when the cursor is
opened and the query is executed.
• Open an explicit cursor several times with a different
active set each time.
CURSOR cursor_name
[(parameter_name datatype, ...)]
IS
select_statement;
OPEN cursor_name(parameter_value,.....) ;
Copyright © 2007, Oracle. All rights reserved.
7 - 194
Cursors with Parameters
DECLARE
CURSOR c_emp_cursor (deptno NUMBER) IS
SELECT employee_id, last_name
FROM employees
WHERE department_id = deptno;
...
BEGIN
OPEN c_emp_cursor (10);
...
CLOSE c_emp_cursor;
OPEN c_emp_cursor (20);
...
Copyright © 2007, Oracle. All rights reserved.
7 - 195
FOR UPDATE Clause
Syntax:
• Use explicit locking to deny access to other sessions for
the duration of a transaction.
• Lock the rows before the update or delete.
SELECT ...
FROM ...
FOR UPDATE [OF column_reference][NOWAIT | WAIT n];
Copyright © 2007, Oracle. All rights reserved.
7 - 197
WHERE CURRENT OF Clause
Syntax:
• Use cursors to update or delete the current row.
• Include the FOR UPDATE clause in the cursor query to
lock the rows first.
• Use the WHERE CURRENT OF clause to reference the
current row from an explicit cursor.
WHERE CURRENT OF cursor ;
UPDATE employees
SET salary = ...
WHERE CURRENT OF c_emp_cursor;
Copyright © 2007, Oracle. All rights reserved.
7 - 198
Cursors with Subqueries
Example:
DECLARE
CURSOR my_cursor IS
SELECT t1.department_id, t1.department_name,
t2.staff
FROM departments t1, (SELECT department_id,
COUNT(*) AS staff
FROM employees
GROUP BY department_id) t2
WHERE t1.department_id = t2.department_id
AND t2.staff >= 3;
...
Copyright © 2007, Oracle. All rights reserved.
7 - 199
Summary
In this lesson, you should have learned how to:
• Distinguish cursor types:
– Implicit cursors are used for all DML statements and
single-row queries.
– Explicit cursors are used for queries of zero, one, or more
rows.
• Create and handle explicit cursors
• Use simple loops and cursor FOR loops to handle
multiple rows in the cursors
• Evaluate the cursor status by using the cursor attributes
• Use the FOR UPDATE and WHERE CURRENT OF clauses
to update or delete the current fetched row
Copyright © 2007, Oracle. All rights reserved.
7 - 200
Practice 7: Overview
This practice covers the following topics:
• Declaring and using explicit cursors to query rows of a
table
• Using a cursor FOR loop
• Applying cursor attributes to test the cursor status
• Declaring and using cursors with parameters
• Using the FOR UPDATE and WHERE CURRENT OF clauses
Copyright © 2007, Oracle. All rights reserved.
Handling Exceptions
Copyright © 2007, Oracle. All rights reserved.
8 - 205
Objectives
After completing this lesson, you should be able to do the
following:
• Define PL/SQL exceptions
• Recognize unhandled exceptions
• List and use different types of PL/SQL exception
handlers
• Trap unanticipated errors
• Describe the effect of exception propagation in nested
blocks
• Customize PL/SQL exception messages
Copyright © 2007, Oracle. All rights reserved.
8 - 206
Example of an Exception
DECLARE
v_lname VARCHAR2(15);
BEGIN
SELECT last_name INTO v_lname
FROM employees
WHERE first_name='John';
DBMS_OUTPUT.PUT_LINE ('John''s last name is :'
||v_lname);
END;
Copyright © 2007, Oracle. All rights reserved.
8 - 207
Example of an Exception
DECLARE
v_lname VARCHAR2(15);
BEGIN
SELECT last_name INTO v_lname
FROM employees
WHERE first_name='John';
DBMS_OUTPUT.PUT_LINE ('John''s last name is :'
||v_lname);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE (' Your select statement
retrieved multiple rows. Consider using a
cursor.');
END;
/
Copyright © 2007, Oracle. All rights reserved.
8 - 208
Handling Exceptions with PL/SQL
• An exception is a PL/SQL error that is raised during
program execution.
• An exception can be raised:
– Implicitly by the Oracle server
– Explicitly by the program
• An exception can be handled:
– By trapping it with a handler
– By propagating it to the calling environment
Copyright © 2007, Oracle. All rights reserved.
8 - 209
Handling Exceptions
Exception
is raised.
Is the
exception
trapped?
Yes
Execute statements
in the EXCEPTION
section.
Terminate
gracefully.
No
Terminate
abruptly.
Propagate the
exception.
Copyright © 2007, Oracle. All rights reserved.
8 - 210
Exception Types
• Predefined Oracle server
• Non-predefined Oracle server
• User-defined
}Implicitly raised
Explicitly raised
Copyright © 2007, Oracle. All rights reserved.
8 - 211
Trapping Exceptions
Syntax:
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
Copyright © 2007, Oracle. All rights reserved.
8 - 213
Guidelines for Trapping Exceptions
• The EXCEPTION keyword starts the exception-handling
section.
• Several exception handlers are allowed.
• Only one handler is processed before leaving the block.
• WHEN OTHERS is the last clause.
Copyright © 2007, Oracle. All rights reserved.
8 - 214
Trapping Predefined Oracle Server Errors
• Reference the predefined name in the exception-
handling routine.
• Sample predefined exceptions:
– NO_DATA_FOUND
– TOO_MANY_ROWS
– INVALID_CURSOR
– ZERO_DIVIDE
– DUP_VAL_ON_INDEX
Copyright © 2007, Oracle. All rights reserved.
8 - 217
Trapping Non-Predefined
Oracle Server Errors
Declarative section
Declare
Name the
exception.
Use PRAGMA
EXCEPTION_INIT.
EXCEPTION section
Handle the raised
exception.
Associate Reference
Copyright © 2007, Oracle. All rights reserved.
8 - 218
DECLARE
e_insert_excep EXCEPTION;
PRAGMA EXCEPTION_INIT(e_insert_excep, -01400);
BEGIN
INSERT INTO departments
(department_id, department_name) VALUES (280, NULL);
EXCEPTION
WHEN e_insert_excep THEN
DBMS_OUTPUT.PUT_LINE('INSERT OPERATION FAILED');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
Non-Predefined Error
To trap Oracle server error number –01400
(“cannot insert NULL”):
1
2
3
Copyright © 2007, Oracle. All rights reserved.
8 - 219
Functions for Trapping Exceptions
• SQLCODE: Returns the numeric value for the error code
• SQLERRM: Returns the message associated with the error
number
Copyright © 2007, Oracle. All rights reserved.
8 - 220
Functions for Trapping Exceptions
Example
DECLARE
error_code NUMBER;
error_message VARCHAR2(255);
BEGIN
...
EXCEPTION
...
WHEN OTHERS THEN
ROLLBACK;
error_code := SQLCODE ;
error_message := SQLERRM ;
INSERT INTO errors (e_user, e_date, error_code,
error_message) VALUES(USER,SYSDATE,error_code,
error_message);
END;
/
Copyright © 2007, Oracle. All rights reserved.
8 - 221
Trapping User-Defined Exceptions
Declarative
section
Name the
exception.
Executable
section
Explicitly raise
the exception by
using the RAISE
statement.
Exception-handling
section
Handle the raised
exception.
Raise Reference
Declare
Copyright © 2007, Oracle. All rights reserved.
8 - 222
Trapping User-Defined Exceptions
DECLARE
v_deptno NUMBER := 500;
v_name VARCHAR2(20) := 'Testing';
e_invalid_department EXCEPTION;
BEGIN
UPDATE departments
SET department_name = v_name
WHERE department_id = v_deptno;
IF SQL % NOTFOUND THEN
RAISE e_invalid_department;
END IF;
COMMIT;
EXCEPTION
WHEN e_invalid_department THEN
DBMS_OUTPUT.PUT_LINE('No such department id.');
END;
/
1
2
3
Copyright © 2007, Oracle. All rights reserved.
8 - 223
Propagating Exceptions in a Subblock
DECLARE
. . .
e_no_rows exception;
e_integrity exception;
PRAGMA EXCEPTION_INIT (e_integrity, -2292);
BEGIN
FOR c_record IN emp_cursor LOOP
BEGIN
SELECT ...
UPDATE ...
IF SQL%NOTFOUND THEN
RAISE e_no_rows;
END IF;
END;
END LOOP;
EXCEPTION
WHEN e_integrity THEN ...
WHEN e_no_rows THEN ...
END;
/
Subblocks can handle
an exception or pass
the exception to the
enclosing block.
Copyright © 2007, Oracle. All rights reserved.
8 - 224
RAISE_APPLICATION_ERROR Procedure
Syntax:
• You can use this procedure to issue user-defined error
messages from stored subprograms.
• You can report errors to your application and avoid
returning unhandled exceptions.
raise_application_error (error_number,
message[, {TRUE | FALSE}]);
Copyright © 2007, Oracle. All rights reserved.
8 - 225
RAISE_APPLICATION_ERROR Procedure
• Used in two different places:
– Executable section
– Exception section
• Returns error conditions to the user in a manner
consistent with other Oracle server errors
Copyright © 2007, Oracle. All rights reserved.
8 - 226
RAISE_APPLICATION_ERROR Procedure
Executable section:
Exception section:
BEGIN
...
DELETE FROM employees
WHERE manager_id = v_mgr;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20202,
'This is not a valid manager');
END IF;
...
...
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (-20201,
'Manager is not a valid employee.');
END;
/
Copyright © 2007, Oracle. All rights reserved.
8 - 227
Summary
In this lesson, you should have learned how to:
• Define PL/SQL exceptions
• Add an EXCEPTION section to the PL/SQL block to deal
with exceptions at run time
• Handle different types of exceptions:
– Predefined exceptions
– Non-predefined exceptions
– User-defined exceptions
• Propagate exceptions in nested blocks and call
applications
Copyright © 2007, Oracle. All rights reserved.
8 - 228
Practice 8: Overview
This practice covers the following topics:
• Handling named exceptions
• Creating and invoking user-defined exceptions
Copyright © 2007, Oracle. All rights reserved.
Creating Stored Procedures and Functions
Copyright © 2007, Oracle. All rights reserved.
9 - 232
Objectives
After completing this lesson, you should be able to do the
following:
• Differentiate between anonymous blocks and
subprograms
• Create a simple procedure and invoke it from an
anonymous block
• Create a simple function
• Create a simple function that accepts a parameter
• Differentiate between procedures and functions
Copyright © 2007, Oracle. All rights reserved.
9 - 233
Procedures and Functions
• Are named PL/SQL blocks
• Are called PL/SQL subprograms
• Have block structures similar to anonymous blocks:
– Optional declarative section (without the DECLARE
keyword)
– Mandatory executable section
– Optional section to handle exceptions
Copyright © 2007, Oracle. All rights reserved.
9 - 234
Differences Between Anonymous
Blocks and Subprograms
Anonymous Blocks Subprograms
Unnamed PL/SQL blocks Named PL/SQL blocks
Compiled every time Compiled only once
Not stored in the database Stored in the database
Cannot be invoked by other
applications
Named and, therefore, can be invoked
by other applications
Do not return values Subprograms called functions must
return values.
Cannot take parameters Can take parameters
Copyright © 2007, Oracle. All rights reserved.
9 - 235
Procedure: Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name
[(argument1 [mode1] datatype1,
argument2 [mode2] datatype2,
. . .)]
IS|AS
procedure_body;
Copyright © 2007, Oracle. All rights reserved.
9 - 236
Procedure: Example
...
CREATE TABLE dept AS SELECT * FROM departments;
CREATE PROCEDURE add_dept IS
v_dept_id dept.department_id%TYPE;
v_dept_name dept.department_name%TYPE;
BEGIN
v_dept_id:=280;
v_dept_name:='ST-Curriculum';
INSERT INTO dept(department_id,department_name)
VALUES(v_dept_id,v_dept_name);
DBMS_OUTPUT.PUT_LINE(' Inserted '|| SQL%ROWCOUNT
||' row ');
END;
Copyright © 2007, Oracle. All rights reserved.
9 - 238
Invoking the Procedure
BEGIN
add_dept;
END;
/
SELECT department_id, department_name FROM dept
WHERE department_id=280;
Copyright © 2007, Oracle. All rights reserved.
9 - 239
Function: Syntax
CREATE [OR REPLACE] FUNCTION function_name
[(argument1 [mode1] datatype1,
argument2 [mode2] datatype2,
. . .)]
RETURN datatype
IS|AS
function_body;
Copyright © 2007, Oracle. All rights reserved.
9 - 240
Function: Example
CREATE FUNCTION check_sal RETURN Boolean IS
v_dept_id employees.department_id%TYPE;
v_empno employees.employee_id%TYPE;
v_sal employees.salary%TYPE;
v_avg_sal employees.salary%TYPE;
BEGIN
v_empno:=205;
SELECT salary,department_id INTO v_sal,v_dept_id FROM
employees
WHERE employee_id= v_empno;
SELECT avg(salary) INTO v_avg_sal FROM employees WHERE
department_id=v_dept_id;
IF v_sal > v_avg_sal THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END;
Copyright © 2007, Oracle. All rights reserved.
9 - 241
Invoking the Function
BEGIN
IF (check_sal IS NULL) THEN
DBMS_OUTPUT.PUT_LINE('The function returned
NULL due to exception');
ELSIF (check_sal) THEN
DBMS_OUTPUT.PUT_LINE('Salary > average');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary < average');
END IF;
END;
/
Copyright © 2007, Oracle. All rights reserved.
9 - 242
Passing a Parameter to the Function
DROP FUNCTION check_sal;
CREATE FUNCTION check_sal(p_empno employees.employee_id%TYPE)
RETURN Boolean IS
v_dept_id employees.department_id%TYPE;
v_sal employees.salary%TYPE;
v_avg_sal employees.salary%TYPE;
BEGIN
SELECT salary,department_id INTO v_sal,v_dept_id FROM employees
WHERE employee_id=p_empno;
SELECT avg(salary) INTO v_avg_sal FROM employees
WHERE department_id=v_dept_id;
IF v_sal > v_avg_sal THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
EXCEPTION
...
Copyright © 2007, Oracle. All rights reserved.
9 - 243
Invoking the Function with a Parameter
BEGIN
DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205');
IF (check_sal(205) IS NULL) THEN
DBMS_OUTPUT.PUT_LINE('The function returned
NULL due to exception');
ELSIF (check_sal(205)) THEN
DBMS_OUTPUT.PUT_LINE('Salary > average');
ELSE
DBMS_OUTPUT.PUT_LINE('Salary < average');
END IF;
DBMS_OUTPUT.PUT_LINE('Checking for employee with id 70');
IF (check_sal(70) IS NULL) THEN
DBMS_OUTPUT.PUT_LINE('The function returned
NULL due to exception');
ELSIF (check_sal(70)) THEN
...
END IF;
END;
/
Copyright © 2007, Oracle. All rights reserved.
9 - 244
Summary
In this lesson, you should have learned how to:
• Create a simple procedure
• Invoke the procedure from an anonymous block
• Create a simple function
• Create a simple function that accepts parameters
• Invoke the function from an anonymous block
Copyright © 2007, Oracle. All rights reserved.
9 - 245
Practice 9: Overview
This practice covers the following topics:
• Converting an existing anonymous block to a procedure
• Modifying the procedure to accept a parameter
• Writing an anonymous block to invoke the procedure

More Related Content

What's hot

05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Proceduresrehaniltifat
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBaseSalman Memon
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle databaseSalman Memon
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group FunctionsSalman Memon
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joinsredro
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Achmad Solichin
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuningGuy Harrison
 
Oracle Forms: create debug triggers
Oracle Forms: create debug triggersOracle Forms: create debug triggers
Oracle Forms: create debug triggersSekhar Byna
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data baseSalman Memon
 
Oracle SQL Developer for SQL Server?
Oracle SQL Developer for SQL Server?Oracle SQL Developer for SQL Server?
Oracle SQL Developer for SQL Server?Jeff Smith
 

What's hot (20)

Les01
Les01Les01
Les01
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
SQL
SQLSQL
SQL
 
Oracle sql joins
Oracle sql joinsOracle sql joins
Oracle sql joins
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
Database Objects
Database ObjectsDatabase Objects
Database Objects
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
 
Oracle Forms: create debug triggers
Oracle Forms: create debug triggersOracle Forms: create debug triggers
Oracle Forms: create debug triggers
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data base
 
Oracle SQL Developer for SQL Server?
Oracle SQL Developer for SQL Server?Oracle SQL Developer for SQL Server?
Oracle SQL Developer for SQL Server?
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
forms builder
forms builderforms builder
forms builder
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 

Similar to Cursores.ppt

1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadatarehaniltifat
 
Less07 schema
Less07 schemaLess07 schema
Less07 schemaImran Ali
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptxKulbir4
 
New PLSQL in Oracle Database 12c
New PLSQL in Oracle Database 12cNew PLSQL in Oracle Database 12c
New PLSQL in Oracle Database 12cConnor McDonald
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusChhom Karath
 
Web Cloud Computing SQL Server - Ferrara University
Web Cloud Computing SQL Server  -  Ferrara UniversityWeb Cloud Computing SQL Server  -  Ferrara University
Web Cloud Computing SQL Server - Ferrara Universityantimo musone
 
Manage schema object.ppt
Manage schema object.pptManage schema object.ppt
Manage schema object.pptAhmadUsman79
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introductionoracle content
 
Database Management Systems SQL And DDL language
Database Management Systems SQL And DDL languageDatabase Management Systems SQL And DDL language
Database Management Systems SQL And DDL languageHSibghatUllah
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 

Similar to Cursores.ppt (20)

1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Less07 schema
Less07 schemaLess07 schema
Less07 schema
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
SQL SELECT Statement
 SQL SELECT Statement SQL SELECT Statement
SQL SELECT Statement
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
 
New PLSQL in Oracle Database 12c
New PLSQL in Oracle Database 12cNew PLSQL in Oracle Database 12c
New PLSQL in Oracle Database 12c
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
Oracle Introduction
Oracle Introduction Oracle Introduction
Oracle Introduction
 
Dbmsunit v
Dbmsunit vDbmsunit v
Dbmsunit v
 
plsql les02
 plsql les02 plsql les02
plsql les02
 
Web Cloud Computing SQL Server - Ferrara University
Web Cloud Computing SQL Server  -  Ferrara UniversityWeb Cloud Computing SQL Server  -  Ferrara University
Web Cloud Computing SQL Server - Ferrara University
 
Manage schema object.ppt
Manage schema object.pptManage schema object.ppt
Manage schema object.ppt
 
Plsql guide 2
Plsql guide 2Plsql guide 2
Plsql guide 2
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
SQL overview and software
SQL overview and softwareSQL overview and software
SQL overview and software
 
Oracle: PLSQL Introduction
Oracle: PLSQL IntroductionOracle: PLSQL Introduction
Oracle: PLSQL Introduction
 
Database Management Systems SQL And DDL language
Database Management Systems SQL And DDL languageDatabase Management Systems SQL And DDL language
Database Management Systems SQL And DDL language
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 

Recently uploaded

VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 

Cursores.ppt

  • 1. Copyright © 2007, Oracle. All rights reserved. Introduction to PL/SQL
  • 2. Copyright © 2007, Oracle. All rights reserved. 1 - 2 Objectives After completing this lesson, you should be able to do the following: • Explain the need for PL/SQL • Explain the benefits of PL/SQL • Identify the different types of PL/SQL blocks • Output messages in PL/SQL
  • 3. Copyright © 2007, Oracle. All rights reserved. 1 - 3 About PL/SQL PL/SQL: • Stands for “Procedural Language extension to SQL” • Is Oracle Corporation’s standard data access language for relational databases • Seamlessly integrates procedural constructs with SQL
  • 4. Copyright © 2007, Oracle. All rights reserved. 1 - 4 About PL/SQL PL/SQL: • Provides a block structure for executable units of code. Maintenance of code is made easier with such a well-defined structure. • Provides procedural constructs such as: – Variables, constants, and data types – Control structures such as conditional statements and loops – Reusable program units that are written once and executed many times
  • 5. Copyright © 2007, Oracle. All rights reserved. 1 - 5 PL/SQL Environment PL/SQL engine Oracle database server SQL statement executor Procedural statement executor procedural SQL PL/SQL block
  • 6. Copyright © 2007, Oracle. All rights reserved. 1 - 6 Benefits of PL/SQL • Integration of procedural constructs with SQL • Improved performance SQL IF...THEN SQL ELSE SQL END IF; SQL SQL 1 SQL 2 …
  • 7. Copyright © 2007, Oracle. All rights reserved. 1 - 7 Benefits of PL/SQL • Modularized program development • Integration with Oracle tools • Portability • Exception handling
  • 8. Copyright © 2007, Oracle. All rights reserved. 1 - 9 PL/SQL Block Structure • DECLARE (optional) – Variables, cursors, user-defined exceptions • BEGIN (mandatory) – SQL statements – PL/SQL statements • EXCEPTION (optional) – Actions to perform when errors occur • END; (mandatory)
  • 9. Copyright © 2007, Oracle. All rights reserved. 1 - 11 Block Types Anonymous Procedure Function [DECLARE] BEGIN --statements [EXCEPTION] END; PROCEDURE name IS BEGIN --statements [EXCEPTION] END; FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
  • 10. Copyright © 2007, Oracle. All rights reserved. 1 - 13 Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Constructs Object types Database triggers Stored packages Stored procedures or functions Anonymous blocks Database Server Constructs Object types
  • 11. Copyright © 2007, Oracle. All rights reserved. 1 - 15 Create an Anonymous Block Enter the anonymous block in the SQL Developer workspace:
  • 12. Copyright © 2007, Oracle. All rights reserved. 1 - 16 Execute an Anonymous Block Click the Run Script button to execute the anonymous block: Run Script
  • 13. Copyright © 2007, Oracle. All rights reserved. 1 - 17 Test the Output of a PL/SQL Block • Enable output in SQL Developer by clicking the Enable DBMS Output button on the DBMS Output tab: • Use a predefined Oracle package and its procedure: – DBMS_OUTPUT.PUT_LINE DBMS_OUTPUT.PUT_LINE(' The First Name of the Employee is ' || f_name); … Enable DBMS Output DBMS Output Tab
  • 14. Copyright © 2007, Oracle. All rights reserved. 1 - 18 Test the Output of a PL/SQL Block
  • 15. Copyright © 2007, Oracle. All rights reserved. 1 - 19 Summary In this lesson, you should have learned how to: • Integrate SQL statements with PL/SQL program constructs • Describe the benefits of PL/SQL • Differentiate between PL/SQL block types • Output messages in PL/SQL
  • 16. Copyright © 2007, Oracle. All rights reserved. 1 - 20 Practice 1: Overview This practice covers the following topics: • Identifying the PL/SQL blocks that execute successfully • Creating and executing a simple PL/SQL block
  • 17. Copyright © 2007, Oracle. All rights reserved. Declaring PL/SQL Variables
  • 18. Copyright © 2007, Oracle. All rights reserved. 2 - 23 Objectives After completing this lesson, you should be able to do the following: • Recognize valid and invalid identifiers • List the uses of variables • Declare and initialize variables • List and describe various data types • Identify the benefits of using the %TYPE attribute • Declare, use, and print bind variables
  • 19. Copyright © 2007, Oracle. All rights reserved. 2 - 24 Use of Variables Variables can be used for: • Temporary storage of data • Manipulation of stored values • Reusability SELECT first_name, department_id INTO v_fname, v_deptno FROM … v_fname v_deptno Jennifer 10
  • 20. Copyright © 2007, Oracle. All rights reserved. 2 - 25 Requirements for Variable Names A variable name: • Must start with a letter • Can include letters or numbers • Can include special characters (such as $, _, and # ) • Must contain no more than 30 characters • Must not include reserved words
  • 21. Copyright © 2007, Oracle. All rights reserved. 2 - 26 Handling Variables in PL/SQL Variables are: • Declared and initialized in the declarative section • Used and assigned new values in the executable section • Passed as parameters to PL/SQL subprograms • Used to hold the output of a PL/SQL subprogram
  • 22. Copyright © 2007, Oracle. All rights reserved. 2 - 27 Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; DECLARE v_hiredate DATE; v_deptno NUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
  • 23. Copyright © 2007, Oracle. All rights reserved. 2 - 28 Declaring and Initializing PL/SQL Variables DECLARE v_myName VARCHAR2(20); BEGIN DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); v_myName := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); END; / DECLARE v_myName VARCHAR2(20):= 'John'; BEGIN v_myName := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '|| v_myName); END; / 1 2
  • 24. Copyright © 2007, Oracle. All rights reserved. 2 - 29 Delimiters in String Literals DECLARE v_event VARCHAR2(15); BEGIN v_event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '|| v_event ); v_event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '|| v_event ); END; /
  • 25. Copyright © 2007, Oracle. All rights reserved. 2 - 30 Types of Variables • PL/SQL variables: – Scalar – Composite – Reference – Large object (LOB) • Non-PL/SQL variables: Bind variables
  • 26. Copyright © 2007, Oracle. All rights reserved. 2 - 31 TRUE Types of Variables 25-JAN-01 Atlanta 256120.08 Snow White Long, long ago, in a land far, far away, there lived a princess called Snow White. . .
  • 27. Copyright © 2007, Oracle. All rights reserved. 2 - 32 Guidelines for Declaring and Initializing PL/SQL Variables • Follow naming conventions. • Use meaningful identifiers for variables. • Initialize variables designated as NOT NULL and CONSTANT. • Initialize variables with the assignment operator (:=) or the DEFAULT keyword: • Declare one identifier per line for better readability and code maintenance. v_myName VARCHAR2(20):='John'; v_myName VARCHAR2(20) DEFAULT 'John';
  • 28. Copyright © 2007, Oracle. All rights reserved. 2 - 33 Guidelines for Declaring PL/SQL Variables • Avoid using column names as identifiers. • Use the NOT NULL constraint when the variable must hold a value. DECLARE employee_id NUMBER(6); BEGIN SELECT employee_id INTO employee_id FROM employees WHERE last_name = 'Kochhar'; END; /
  • 29. Copyright © 2007, Oracle. All rights reserved. 2 - 34 Scalar Data Types • Hold a single value • Have no internal components Atlanta TRUE 25-JAN-01 256120.08 The soul of the lazy man desires, and he has nothing; but the soul of the diligent shall be made rich.
  • 30. Copyright © 2007, Oracle. All rights reserved. 2 - 35 Base Scalar Data Types • CHAR [(maximum_length)] • VARCHAR2 (maximum_length) • NUMBER [(precision, scale)] • BINARY_INTEGER • PLS_INTEGER • BOOLEAN • BINARY_FLOAT • BINARY_DOUBLE
  • 31. Copyright © 2007, Oracle. All rights reserved. 2 - 37 Base Scalar Data Types • DATE • TIMESTAMP • TIMESTAMP WITH TIME ZONE • TIMESTAMP WITH LOCAL TIME ZONE • INTERVAL YEAR TO MONTH • INTERVAL DAY TO SECOND
  • 32. Copyright © 2007, Oracle. All rights reserved. 2 - 39 Declaring Scalar Variables Examples: DECLARE v_emp_job VARCHAR2(9); v_count_loop BINARY_INTEGER := 0; v_dept_total_sal NUMBER(9,2) := 0; v_orderdate DATE := SYSDATE + 7; c_tax_rate CONSTANT NUMBER(3,2) := 8.25; v_valid BOOLEAN NOT NULL := TRUE; ...
  • 33. Copyright © 2007, Oracle. All rights reserved. 2 - 40 %TYPE Attribute • Is used to declare a variable according to: – A database column definition – Another declared variable • Is prefixed with: – The database table and column – The name of the declared variable
  • 34. Copyright © 2007, Oracle. All rights reserved. 2 - 42 Declaring Variables with the %TYPE Attribute Syntax Examples ... emp_lname employees.last_name%TYPE; ... identifier table.column_name%TYPE; ... balance NUMBER(7,2); min_balance balance%TYPE := 1000; ...
  • 35. Copyright © 2007, Oracle. All rights reserved. 2 - 43 Declaring Boolean Variables • Only the TRUE, FALSE, and NULL values can be assigned to a Boolean variable. • Conditional expressions use the logical operators AND and OR and the unary operator NOT to check the variable values. • The variables always yield TRUE, FALSE, or NULL. • Arithmetic, character, and date expressions can be used to return a Boolean value.
  • 36. Copyright © 2007, Oracle. All rights reserved. 2 - 44 Bind Variables Bind variables are: • Created in the environment • Also called host variables • Created with the VARIABLE keyword • Used in SQL statements and PL/SQL blocks • Accessed even after the PL/SQL block is executed • Referenced with a preceding colon
  • 37. Copyright © 2007, Oracle. All rights reserved. 2 - 46 Printing Bind Variables Example: VARIABLE b_emp_salary NUMBER BEGIN SELECT salary INTO :b_emp_salary FROM employees WHERE employee_id = 178; END; / PRINT b_emp_salary SELECT first_name, last_name FROM employees WHERE salary=:b_emp_salary;
  • 38. Copyright © 2007, Oracle. All rights reserved. 2 - 47 Printing Bind Variables Example: VARIABLE b_emp_salary NUMBER SET AUTOPRINT ON DECLARE v_empno NUMBER(6):=&empno; BEGIN SELECT salary INTO :b_emp_salary FROM employees WHERE employee_id = v_empno; END; 7000 Output:
  • 39. Copyright © 2007, Oracle. All rights reserved. 2 - 48 LOB Data Type Variables Book (CLOB) Photo (BLOB) Movie (BFILE) NCLOB
  • 40. Copyright © 2007, Oracle. All rights reserved. 2 - 49 Composite Data Types TRUE 23-DEC-98 ATLANTA 1 5000 2 2345 3 12 4 3456 1 SMITH 2 JONES 3 NANCY 4 TIM PL/SQL table structure PL/SQL table structure PLS_INTEGER VARCHAR2 PLS_INTEGER NUMBER
  • 41. Copyright © 2007, Oracle. All rights reserved. 2 - 50 Summary In this lesson, you should have learned how to: • Recognize valid and invalid identifiers • Declare variables in the declarative section of a PL/SQL block • Initialize variables and use them in the executable section • Differentiate between scalar and composite data types • Use the %TYPE attribute • Use bind variables
  • 42. Copyright © 2007, Oracle. All rights reserved. 2 - 51 Practice 2: Overview This practice covers the following topics: • Determining valid identifiers • Determining valid variable declarations • Declaring variables within an anonymous block • Using the %TYPE attribute to declare variables • Declaring and printing a bind variable • Executing a PL/SQL block
  • 43. Copyright © 2007, Oracle. All rights reserved. Writing Executable Statements
  • 44. Copyright © 2007, Oracle. All rights reserved. 3 - 55 Objectives After completing this lesson, you should be able to do the following: • Identify lexical units in a PL/SQL block • Use built-in SQL functions in PL/SQL • Describe when implicit conversions take place and when explicit conversions have to be dealt with • Write nested blocks and qualify variables with labels • Write readable code with appropriate indentation • Use sequences in PL/SQL expressions
  • 45. Copyright © 2007, Oracle. All rights reserved. 3 - 56 Lexical Units in a PL/SQL Block Lexical units: • Are building blocks of any PL/SQL block • Are sequences of characters including letters, numerals, tabs, spaces, returns, and symbols • Can be classified as: – Identifiers: v_fname, c_percent – Delimiters: ; , +, - – Literals: John, 428, True – Comments: --, /* */
  • 46. Copyright © 2007, Oracle. All rights reserved. 3 - 58 PL/SQL Block Syntax and Guidelines • Literals – Character and date literals must be enclosed in single quotation marks. – Numbers can be simple values or in scientific notation. • Statements can span several lines. name := 'Henderson'; 1 2 3
  • 47. Copyright © 2007, Oracle. All rights reserved. 3 - 59 Commenting Code • Prefix single-line comments with two hyphens (--). • Place multiple-line comments between the symbols /* and */. Example: DECLARE ... v_annual_sal NUMBER (9,2); BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_annual_sal := monthly_sal * 12; --The following line displays the annual salary DBMS_OUTPUT.PUT_LINE(v_annual_sal); END; /
  • 48. Copyright © 2007, Oracle. All rights reserved. 3 - 60 SQL Functions in PL/SQL • Available in procedural statements: – Single-row functions • Not available in procedural statements: – DECODE – Group functions
  • 49. Copyright © 2007, Oracle. All rights reserved. 3 - 61 SQL Functions in PL/SQL: Examples • Get the length of a string: • Get the number of months an employee has worked: v_desc_size INTEGER(5); v_prod_description VARCHAR2(70):='You can use this product with your radios for higher frequency'; -- get the length of the string in prod_description v_desc_size:= LENGTH(prod_description); v_tenure:= MONTHS_BETWEEN (CURRENT_DATE, v_hiredate);
  • 50. Copyright © 2007, Oracle. All rights reserved. 3 - 62 Using Sequences in PL/SQL Expressions Starting in 11g: Before 11g: DECLARE v_new_id NUMBER; BEGIN SELECT my_seq.NEXTVAL INTO v_new_id FROM Dual; END; / DECLARE v_new_id NUMBER; BEGIN v_new_id := my_seq.NEXTVAL; END; /
  • 51. Copyright © 2007, Oracle. All rights reserved. 3 - 63 Data Type Conversion • Converts data to comparable data types • Is of two types: – Implicit conversion – Explicit conversion • Functions: – TO_CHAR – TO_DATE – TO_NUMBER – TO_TIMESTAMP
  • 52. Copyright © 2007, Oracle. All rights reserved. 3 - 65 Data Type Conversion date_of_joining DATE:= '02-Feb-2000'; date_of_joining DATE:= 'February 02,2000'; date_of_joining DATE:= TO_DATE('February 02,2000','Month DD, YYYY'); 1 2 3
  • 53. Copyright © 2007, Oracle. All rights reserved. 3 - 66 Nested Blocks PL/SQL blocks can be nested. • An executable section (BEGIN … END) can contain nested blocks. • An exception section can contain nested blocks.
  • 54. Copyright © 2007, Oracle. All rights reserved. 3 - 67 Nested Blocks Example: DECLARE v_outer_variable VARCHAR2(20):='GLOBAL VARIABLE'; BEGIN DECLARE v_inner_variable VARCHAR2(20):='LOCAL VARIABLE'; BEGIN DBMS_OUTPUT.PUT_LINE(v_inner_variable); DBMS_OUTPUT.PUT_LINE(v_outer_variable); END; DBMS_OUTPUT.PUT_LINE(v_outer_variable); END;
  • 55. Copyright © 2007, Oracle. All rights reserved. 3 - 68 Variable Scope and Visibility DECLARE v_father_name VARCHAR2(20):='Patrick'; v_date_of_birth DATE:='20-Apr-1972'; BEGIN DECLARE v_child_name VARCHAR2(20):='Mike'; v_date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name); END; DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth); END; / 1 2
  • 56. Copyright © 2007, Oracle. All rights reserved. 3 - 70 Qualify an Identifier BEGIN <<outer>> DECLARE v_father_name VARCHAR2(20):='Patrick'; v_date_of_birth DATE:='20-Apr-1972'; BEGIN DECLARE v_child_name VARCHAR2(20):='Mike'; v_date_of_birth DATE:='12-Dec-2002'; BEGIN DBMS_OUTPUT.PUT_LINE('Father''s Name: '||v_father_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: ' ||outer.v_date_of_birth); DBMS_OUTPUT.PUT_LINE('Child''s Name: '||v_child_name); DBMS_OUTPUT.PUT_LINE('Date of Birth: '||v_date_of_birth); END; END; END outer;
  • 57. Copyright © 2007, Oracle. All rights reserved. 3 - 71 Quiz: Determining Variable Scope BEGIN <<outer>> DECLARE v_sal NUMBER(7,2) := 60000; v_comm NUMBER(7,2) := v_sal * 0.20; v_message VARCHAR2(255) := ' eligible for commission'; BEGIN DECLARE v_sal NUMBER(7,2) := 50000; v_comm NUMBER(7,2) := 0; v_total_comp NUMBER(7,2) := v_sal + v_comm; BEGIN v_message := 'CLERK not'||v_message; outer.v_comm := v_sal * 0.30; END; v_message := 'SALESMAN'||v_message; END; END outer; / 1 2
  • 58. Copyright © 2007, Oracle. All rights reserved. 3 - 73 Operators in PL/SQL • Logical • Arithmetic • Concatenation • Parentheses to control order of operations • Exponential operator (**) Same as in SQL }
  • 59. Copyright © 2007, Oracle. All rights reserved. 3 - 74 Operators in PL/SQL: Examples • Increment the counter for a loop. • Set the value of a Boolean flag. • Validate whether an employee number contains a value. loop_count := loop_count + 1; good_sal := sal BETWEEN 50000 AND 150000; valid := (empno IS NOT NULL);
  • 60. Copyright © 2007, Oracle. All rights reserved. 3 - 75 Programming Guidelines Make code maintenance easier by: • Documenting code with comments • Developing a case convention for the code • Developing naming conventions for identifiers and other objects • Enhancing readability by indenting
  • 61. Copyright © 2007, Oracle. All rights reserved. 3 - 76 Indenting Code For clarity, indent each level of code. BEGIN IF x=0 THEN y:=1; END IF; END; / DECLARE deptno NUMBER(4); location_id NUMBER(4); BEGIN SELECT department_id, location_id INTO deptno, location_id FROM departments WHERE department_name = 'Sales'; ... END; /
  • 62. Copyright © 2007, Oracle. All rights reserved. 3 - 77 Summary In this lesson, you should have learned how to: • Identify lexical units in a PL/SQL block • Use built-in SQL functions in PL/SQL • Write nested blocks to break logically related functionalities • Decide when to perform explicit conversions • Qualify variables in nested blocks • Use sequences in PL/SQL expressions
  • 63. Copyright © 2007, Oracle. All rights reserved. 3 - 78 Practice 3: Overview This practice covers the following topics: • Reviewing scoping and nesting rules • Writing and testing PL/SQL blocks
  • 64. Copyright © 2007, Oracle. All rights reserved. Interacting with the Oracle Database Server
  • 65. Copyright © 2007, Oracle. All rights reserved. 4 - 83 Objectives After completing this lesson, you should be able to do the following: • Determine the SQL statements that can be directly included in a PL/SQL executable block • Manipulate data with DML statements in PL/SQL • Use transaction control statements in PL/SQL • Make use of the INTO clause to hold the values returned by a SQL statement • Differentiate between implicit cursors and explicit cursors • Use SQL cursor attributes
  • 66. Copyright © 2007, Oracle. All rights reserved. 4 - 84 SQL Statements in PL/SQL • Retrieve a row from the database by using the SELECT command. • Make changes to rows in the database by using DML commands. • Control a transaction with the COMMIT, ROLLBACK, or SAVEPOINT command.
  • 67. Copyright © 2007, Oracle. All rights reserved. 4 - 85 SELECT Statements in PL/SQL Retrieve data from the database with a SELECT statement. Syntax: SELECT select_list INTO {variable_name[, variable_name]... | record_name} FROM table [WHERE condition];
  • 68. Copyright © 2007, Oracle. All rights reserved. 4 - 87 SELECT Statements in PL/SQL • The INTO clause is required. • Queries must return only one row. Example: DECLARE v_fname VARCHAR2(25); BEGIN SELECT first_name INTO v_fname FROM employees WHERE employee_id=200; DBMS_OUTPUT.PUT_LINE(' First Name is : '||v_fname); END; /
  • 69. Copyright © 2007, Oracle. All rights reserved. 4 - 89 Retrieving Data in PL/SQL Retrieve hire_date and salary for the specified employee. Example: DECLARE v_emp_hiredate employees.hire_date%TYPE; v_emp_salary employees.salary%TYPE; BEGIN SELECT hire_date, salary INTO v_emp_hiredate, v_emp_salary FROM employees WHERE employee_id = 100; END; /
  • 70. Copyright © 2007, Oracle. All rights reserved. 4 - 90 DECLARE v_sum_sal NUMBER(10,2); v_deptno NUMBER NOT NULL := 60; BEGIN SELECT SUM(salary) -- group function INTO v_sum_sal FROM employees WHERE department_id = v_deptno; DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal); END; Retrieving Data in PL/SQL Return the sum of the salaries for all the employees in the specified department. Example:
  • 71. Copyright © 2007, Oracle. All rights reserved. 4 - 91 Naming Conventions DECLARE hire_date employees.hire_date%TYPE; sysdate hire_date%TYPE; employee_id employees.employee_id%TYPE := 176; BEGIN SELECT hire_date, sysdate INTO hire_date, sysdate FROM employees WHERE employee_id = employee_id; END; /
  • 72. Copyright © 2007, Oracle. All rights reserved. 4 - 92 Naming Conventions • Use a naming convention to avoid ambiguity in the WHERE clause. • Avoid using database column names as identifiers. • Syntax errors can arise because PL/SQL checks the database first for a column in the table. • The names of local variables and formal parameters take precedence over the names of database tables. • The names of database table columns take precedence over the names of local variables.
  • 73. Copyright © 2007, Oracle. All rights reserved. 4 - 93 Using PL/SQL to Manipulate Data Make changes to database tables by using DML commands: • INSERT • UPDATE • DELETE • MERGE INSERT UPDATE DELETE MERGE
  • 74. Copyright © 2007, Oracle. All rights reserved. 4 - 94 Inserting Data Add new employee information to the EMPLOYEES table. Example: BEGIN INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary) VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES',CURRENT_DATE, 'AD_ASST', 4000); END; /
  • 75. Copyright © 2007, Oracle. All rights reserved. 4 - 95 Updating Data Increase the salary of all employees who are stock clerks. Example: DECLARE sal_increase employees.salary%TYPE := 800; BEGIN UPDATE employees SET salary = salary + sal_increase WHERE job_id = 'ST_CLERK'; END; /
  • 76. Copyright © 2007, Oracle. All rights reserved. 4 - 96 Deleting Data Delete rows that belong to department 10 from the employees table. Example: DECLARE deptno employees.department_id%TYPE := 10; BEGIN DELETE FROM employees WHERE department_id = deptno; END; /
  • 77. Copyright © 2007, Oracle. All rights reserved. 4 - 97 Merging Rows Insert or update rows in the copy_emp table to match the employees table. BEGIN MERGE INTO copy_emp c USING employees e ON (e.employee_id = c.empno) WHEN MATCHED THEN UPDATE SET c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email, . . . WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name, . . .,e.department_id); END; /
  • 78. Copyright © 2007, Oracle. All rights reserved. 4 - 99 SQL Cursor • A cursor is a pointer to the private memory area allocated by the Oracle server. • A cursor is used to handle the result set of a SELECT statement. • There are two types of cursors: – Implicit: Created and managed internally by the Oracle server to process SQL statements – Explicit: Declared explicitly by the programmer
  • 79. Copyright © 2007, Oracle. All rights reserved. 4 - 101 SQL Cursor Attributes for Implicit Cursors Using SQL cursor attributes, you can test the outcome of your SQL statements. SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement returned at least one row SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement did not return even one row SQL%ROWCOUNT An integer value that represents the number of rows affected by the most recent SQL statement
  • 80. Copyright © 2007, Oracle. All rights reserved. 4 - 102 SQL Cursor Attributes for Implicit Cursors Delete rows that have the specified employee ID from the employees table. Print the number of rows deleted. Example: DECLARE v_rows_deleted VARCHAR2(30) v_empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM employees WHERE employee_id = v_empno; v_rows_deleted := (SQL%ROWCOUNT || ' row deleted.'); DBMS_OUTPUT.PUT_LINE (v_rows_deleted); END;
  • 81. Copyright © 2007, Oracle. All rights reserved. 4 - 103 Summary In this lesson, you should have learned how to: • Embed DML statements, transaction control statements, and DDL statements in PL/SQL • Use the INTO clause, which is mandatory for all SELECT statements in PL/SQL • Differentiate between implicit cursors and explicit cursors • Use SQL cursor attributes to determine the outcome of SQL statements
  • 82. Copyright © 2007, Oracle. All rights reserved. 4 - 104 Practice 4: Overview This practice covers the following topics: • Selecting data from a table • Inserting data into a table • Updating data in a table • Deleting a record from a table
  • 83. Copyright © 2007, Oracle. All rights reserved. Writing Control Structures
  • 84. Copyright © 2007, Oracle. All rights reserved. 5 - 108 Objectives After completing this lesson, you should be able to do the following: • Identify the uses and types of control structures • Construct an IF statement • Use CASE statements and CASE expressions • Construct and identify loop statements • Use guidelines when using conditional control structures
  • 85. Copyright © 2007, Oracle. All rights reserved. 5 - 109 Controlling Flow of Execution for loop while
  • 86. Copyright © 2007, Oracle. All rights reserved. 5 - 110 IF Statement Syntax: IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF;
  • 87. Copyright © 2007, Oracle. All rights reserved. 5 - 112 Simple IF Statement DECLARE v_myage number:=31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); END IF; END; / Output:
  • 88. Copyright © 2007, Oracle. All rights reserved. 5 - 113 IF THEN ELSE Statement DECLARE v_myage number:=31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; / Output:
  • 89. Copyright © 2007, Oracle. All rights reserved. 5 - 114 IF ELSIF ELSE Clause DECLARE v_myage number:=31; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF v_myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF v_myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties'); ELSIF v_myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF; END; / Output:
  • 90. Copyright © 2007, Oracle. All rights reserved. 5 - 115 NULL Value in IF Statement DECLARE v_myage number; BEGIN IF v_myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
  • 91. Copyright © 2007, Oracle. All rights reserved. 5 - 116 CASE Expressions • A CASE expression selects a result and returns it. • To select the result, the CASE expression uses expressions. The value returned by these expressions is used to select one of several alternatives. CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1] END; /
  • 92. Copyright © 2007, Oracle. All rights reserved. 5 - 117 CASE Expressions: Example SET VERIFY OFF DECLARE v_grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || ' Appraisal ' || appraisal); END; /
  • 93. Copyright © 2007, Oracle. All rights reserved. 5 - 118 Searched CASE Expressions DECLARE v_grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE WHEN v_grade = 'A' THEN 'Excellent' WHEN v_grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade || ' Appraisal ' || appraisal); END; /
  • 94. Copyright © 2007, Oracle. All rights reserved. 5 - 119 CASE Statement DECLARE v_deptid NUMBER; v_deptname VARCHAR2(20); v_emps NUMBER; v_mngid NUMBER:= 108; BEGIN CASE v_mngid WHEN 108 THEN SELECT department_id, department_name INTO v_deptid, v_deptname FROM departments WHERE manager_id=108; SELECT count(*) INTO v_emps FROM employees WHERE department_id=v_deptid; WHEN 200 THEN ... END CASE; DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname|| ' department. There are '||v_emps ||' employees in this department'); END; /
  • 95. Copyright © 2007, Oracle. All rights reserved. 5 - 120 Handling Nulls When working with nulls, you can avoid some common mistakes by keeping in mind the following rules: • Simple comparisons involving nulls always yield NULL. • Applying the logical operator NOT to a null yields NULL. • If the condition yields NULL in conditional control statements, its associated sequence of statements is not executed.
  • 96. Copyright © 2007, Oracle. All rights reserved. 5 - 121 Logic Tables Build a simple Boolean condition with a comparison operator. AND TRUE FALSE NULL TRUE FALSE NULL TRUE NULL NULL NULL FALSE FALSE FALSE FALSE FALSE NOT TRUE FALSE NULL FALSE TRUE NULL TRUE NULL OR TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE NULL NULL NULL FALSE
  • 97. Copyright © 2007, Oracle. All rights reserved. 5 - 122 Boolean Conditions What is the value of flag in each case? REORDER_FLAG AVAILABLE_FLAG FLAG TRUE TRUE TRUE FALSE NULL TRUE NULL FALSE flag := reorder_flag AND available_flag; ? (1) ? (2) ? (3) ? (4)
  • 98. Copyright © 2007, Oracle. All rights reserved. 5 - 123 Iterative Control: LOOP Statements • Loops repeat a statement (or sequence of statements) multiple times. • There are three loop types: – Basic loop – FOR loop – WHILE loop
  • 99. Copyright © 2007, Oracle. All rights reserved. 5 - 124 Basic Loops Syntax: LOOP statement1; . . . EXIT [WHEN condition]; END LOOP;
  • 100. Copyright © 2007, Oracle. All rights reserved. 5 - 125 DECLARE v_countryid locations.country_id%TYPE := 'CA'; v_loc_id locations.location_id%TYPE; v_counter NUMBER(2) := 1; v_new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = v_countryid; LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), v_new_city, v_countryid); v_counter := v_counter + 1; EXIT WHEN v_counter > 3; END LOOP; END; / Basic Loops Example:
  • 101. Copyright © 2007, Oracle. All rights reserved. 5 - 126 WHILE Loops Syntax: Use the WHILE loop to repeat statements while a condition is TRUE. WHILE condition LOOP statement1; statement2; . . . END LOOP;
  • 102. Copyright © 2007, Oracle. All rights reserved. 5 - 127 WHILE Loops Example DECLARE v_countryid locations.country_id%TYPE := 'CA'; v_loc_id locations.location_id%TYPE; v_new_city locations.city%TYPE := 'Montreal'; v_counter NUMBER := 1; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = v_countryid; WHILE v_counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + v_counter), v_new_city, v_countryid); v_counter := v_counter + 1; END LOOP; END; /
  • 103. Copyright © 2007, Oracle. All rights reserved. 5 - 128 FOR Loops • Use a FOR loop to shortcut the test for the number of iterations. • Do not declare the counter; it is declared implicitly. FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
  • 104. Copyright © 2007, Oracle. All rights reserved. 5 - 130 FOR Loops Example: DECLARE v_countryid locations.country_id%TYPE := 'CA'; v_loc_id locations.location_id%TYPE; v_new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = v_countryid; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((v_loc_id + i), v_new_city, v_countryid ); END LOOP; END; /
  • 105. Copyright © 2007, Oracle. All rights reserved. 5 - 131 FOR Loops Guidelines • Reference the counter within the loop only; it is undefined outside the loop. • Do not reference the counter as the target of an assignment. • Neither loop bound should be NULL.
  • 106. Copyright © 2007, Oracle. All rights reserved. 5 - 132 Guidelines for Loops • Use the basic loop when the statements inside the loop must execute at least once. • Use the WHILE loop if the condition must be evaluated at the start of each iteration. • Use a FOR loop if the number of iterations is known.
  • 107. Copyright © 2007, Oracle. All rights reserved. 5 - 133 Nested Loops and Labels • You can nest loops to multiple levels. • Use labels to distinguish between blocks and loops. • Exit the outer loop with the EXIT statement that references the label.
  • 108. Copyright © 2007, Oracle. All rights reserved. 5 - 134 Nested Loops and Labels ... BEGIN <<Outer_loop>> LOOP v_counter := v_counter+1; EXIT WHEN v_counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop; ... END LOOP Outer_loop; END; /
  • 109. Copyright © 2007, Oracle. All rights reserved. 5 - 135 PL/SQL CONTINUE Statement • Definition – Adds the functionality to begin the next loop iteration – Provides programmers with the ability to transfer control to the next iteration of a loop – Uses parallel structure and semantics to the EXIT statement • Benefits – Eases the programming process – May see a small performance improvement over the previous programming workarounds to simulate the CONTINUE statement
  • 110. Copyright © 2007, Oracle. All rights reserved. 5 - 136 PL/SQL CONTINUE Statement: Example DECLARE v_total SIMPLE_INTEGER := 0; BEGIN FOR i IN 1..10 LOOP v_total := v_total + i; dbms_output.put_line ('Total is: '|| v_total); CONTINUE WHEN i > 5; v_total := v_total + i; dbms_output.put_line ('Out of Loop Total is: '|| v_total); END LOOP; END; / 1 2 anonymous block completed Total is: 1 Out of Loop Total is: 2 Total is: 4 Out of Loop Total is: 6 Total is: 9 Out of Loop Total is: 12 Total is: 16 Out of Loop Total is: 20 Total is: 25 Out of Loop Total is: 30 Total is: 36 Total is: 43 Total is: 51 Total is: 60 Total is: 70
  • 111. Copyright © 2007, Oracle. All rights reserved. 5 - 137 PL/SQL CONTINUE Statement: Example DECLARE v_total NUMBER := 0; BEGIN <<BeforeTopLoop>> FOR i IN 1..10 LOOP v_total := v_total + 1; dbms_output.put_line ('Total is: ' || v_total); FOR j IN 1..10 LOOP CONTINUE BeforeTopLoop WHEN i + j > 5; v_total := v_total + 1; END LOOP; END LOOP; END two_loop; anonymous block completed Total is: 1 Total is: 6 Total is: 10 Total is: 13 Total is: 15 Total is: 16 Total is: 17 Total is: 18 Total is: 19 Total is: 20
  • 112. Copyright © 2007, Oracle. All rights reserved. 5 - 138 Summary In this lesson, you should have learned how to change the logical flow of statements by using the following control structures: • Conditional (IF statement) • CASE expressions and CASE statements • Loops: – Basic loop – FOR loop – WHILE loop • EXIT statement • CONTINUE statement
  • 113. Copyright © 2007, Oracle. All rights reserved. 5 - 139 Practice 5: Overview This practice covers the following topics: • Performing conditional actions by using IF statements • Performing iterative steps by using LOOP structures
  • 114. Copyright © 2007, Oracle. All rights reserved. Working with Composite Data Types
  • 115. Copyright © 2007, Oracle. All rights reserved. 6 - 143 Objectives After completing this lesson, you should be able to do the following: • Create user-defined PL/SQL records • Create a record with the %ROWTYPE attribute • Create an INDEX BY table • Create an INDEX BY table of records • Describe the differences among records, tables, and tables of records
  • 116. Copyright © 2007, Oracle. All rights reserved. 6 - 144 Composite Data Types • Can hold multiple values (unlike scalar types) • Are of two types: – PL/SQL records – PL/SQL collections — INDEX BY tables or associative arrays — Nested table — VARRAY
  • 117. Copyright © 2007, Oracle. All rights reserved. 6 - 145 Composite Data Types • Use PL/SQL records when you want to store values of different data types but only one occurrence at a time. • Use PL/SQL collections when you want to store values of the same data type.
  • 118. Copyright © 2007, Oracle. All rights reserved. 6 - 146 PL/SQL Records • Must contain one or more components (called fields) of any scalar, RECORD, or INDEX BY table data type • Are similar to structures in most third-generation languages (including C and C++) • Are user defined and can be a subset of a row in a table • Treat a collection of fields as a logical unit • Are convenient for fetching a row of data from a table for processing
  • 119. Copyright © 2007, Oracle. All rights reserved. 6 - 147 Creating a PL/SQL Record Syntax: TYPE type_name IS RECORD (field_declaration[, field_declaration]…); field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr] identifier type_name; 1 2 field_declaration:
  • 120. Copyright © 2007, Oracle. All rights reserved. 6 - 148 Creating a PL/SQL Record Declare variables to store the name, job, and salary of a new employee. Example: DECLARE type t_rec is record (v_sal number(8), v_minsal number(8) default 1000, v_hire_date employees.hire_date%type, v_rec1 employees%rowtype); v_myrec t_rec; BEGIN v_myrec.v_sal := v_myrec.v_minsal + 500; v_myrec.v_hire_date := sysdate; SELECT * INTO v_myrec.v_rec1 FROM employees WHERE employee_id = 100; DBMS_OUTPUT.PUT_LINE(v_myrec.v_rec1.last_name ||' '|| to_char(v_myrec.v_hire_date) ||' '|| to_char(v_myrec.v_sal)); END;
  • 121. Copyright © 2007, Oracle. All rights reserved. 6 - 149 PL/SQL Record Structure Example: 100 King AD_PRES employee_id number(6) last_name varchar2(25) job_id varchar2(10) Field2 (data type) Field3 (data type) Field1 (data type) Field2 (data type) Field3 (data type) Field1 (data type)
  • 122. Copyright © 2007, Oracle. All rights reserved. 6 - 150 %ROWTYPE Attribute • Declare a variable according to a collection of columns in a database table or view. • Prefix %ROWTYPE with the database table or view. • Fields in the record take their names and data types from the columns of the table or view. Syntax: DECLARE identifier reference%ROWTYPE;
  • 123. Copyright © 2007, Oracle. All rights reserved. 6 - 152 Advantages of Using %ROWTYPE • The number and data types of the underlying database columns need not be known—and, in fact, might change at run time. • The %ROWTYPE attribute is useful when retrieving a row with the SELECT * statement.
  • 124. Copyright © 2007, Oracle. All rights reserved. 6 - 153 %ROWTYPE Attribute: Example DECLARE v_employee_number number:= 124; v_emp_rec employees%ROWTYPE; BEGIN SELECT * INTO v_emp_rec FROM employees WHERE employee_id = v_employee_number; INSERT INTO retired_emps(empno, ename, job, mgr, hiredate, leavedate, sal, comm, deptno) VALUES (v_emp_rec.employee_id, v_emp_rec.last_name, v_emp_rec.job_id, v_emp_rec.manager_id, v_emp_rec.hire_date, SYSDATE, v_emp_rec.salary, v_emp_rec.commission_pct, v_emp_rec.department_id); END; /
  • 125. Copyright © 2007, Oracle. All rights reserved. 6 - 154 Inserting a Record by Using %ROWTYPE ... DECLARE v_employee_number number:= 124; v_emp_rec retired_emps%ROWTYPE; BEGIN SELECT employee_id, last_name, job_id, manager_id, hire_date, hire_date, salary, commission_pct, department_id INTO v_emp_rec FROM employees WHERE employee_id = v_employee_number; INSERT INTO retired_emps VALUES v_emp_rec; END; / SELECT * FROM retired_emps;
  • 126. Copyright © 2007, Oracle. All rights reserved. 6 - 155 Updating a Row in a Table by Using a Record SET VERIFY OFF DECLARE v_employee_number number:= 124; v_emp_rec retired_emps%ROWTYPE; BEGIN SELECT * INTO v_emp_rec FROM retired_emps; v_emp_rec.leavedate:=CURRENT_DATE; UPDATE retired_emps SET ROW = v_emp_rec WHERE empno=v_employee_number; END; / SELECT * FROM retired_emps;
  • 127. Copyright © 2007, Oracle. All rights reserved. 6 - 156 INDEX BY Tables or Associative Arrays • Are PL/SQL structures with two columns: – Primary key of integer or string data type – Column of scalar or record data type • Are unconstrained in size. However, the size depends on the values that the key data type can hold.
  • 128. Copyright © 2007, Oracle. All rights reserved. 6 - 157 Creating an INDEX BY Table Syntax: Declare an INDEX BY table to store the last names of employees: TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] | table%ROWTYPE [INDEX BY PLS_INTEGER | BINARY_INTEGER | VARCHAR2(<size>)]; identifier type_name; ... TYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY PLS_INTEGER; ... ename_table ename_table_type;
  • 129. Copyright © 2007, Oracle. All rights reserved. 6 - 159 INDEX BY Table Structure Unique key Value ... ... 1 Jones 5 Smith 3 Maduro ... ... PLS_INTEGER Scalar
  • 130. Copyright © 2007, Oracle. All rights reserved. 6 - 160 Creating an INDEX BY Table DECLARE TYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY PLS_INTEGER; TYPE hiredate_table_type IS TABLE OF DATE INDEX BY PLS_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type; BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.EXISTS(1) THEN INSERT INTO ... ... END; /
  • 131. Copyright © 2007, Oracle. All rights reserved. 6 - 161 Using INDEX BY Table Methods The following methods make INDEX BY tables easier to use: • EXISTS • COUNT • FIRST • LAST • PRIOR • NEXT • DELETE
  • 132. Copyright © 2007, Oracle. All rights reserved. 6 - 162 INDEX BY Table of Records Define an INDEX BY table variable to hold an entire row from a table. Example: DECLARE TYPE dept_table_type IS TABLE OF departments%ROWTYPE INDEX BY VARCHAR2(20); dept_table dept_table_type; -- Each element of dept_table is a record
  • 133. Copyright © 2007, Oracle. All rights reserved. 6 - 164 INDEX BY Table of Records: Example DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table emp_table_type; max_count NUMBER(3):= 104; BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END; /
  • 134. Copyright © 2007, Oracle. All rights reserved. 6 - 165 Nested Tables 1 2 3 4 .. 2 GB Bombay Sydney Oxford London ....
  • 135. Copyright © 2007, Oracle. All rights reserved. 6 - 167 Bombay Sydney Oxford London .... VARRAY Tokyo 1 2 3 4 .. 10
  • 136. Copyright © 2007, Oracle. All rights reserved. 6 - 168 Summary In this lesson, you should have learned how to: • Define and reference PL/SQL variables of composite data types – PL/SQL record – INDEX BY table – INDEX BY table of records • Define a PL/SQL record by using the %ROWTYPE attribute
  • 137. Copyright © 2007, Oracle. All rights reserved. 6 - 169 Practice 6: Overview This practice covers the following topics: • Declaring INDEX BY tables • Processing data by using INDEX BY tables • Declaring a PL/SQL record • Processing data by using a PL/SQL record
  • 138. Copyright © 2007, Oracle. All rights reserved. Using Explicit Cursors
  • 139. Copyright © 2007, Oracle. All rights reserved. 7 - 174 Objectives After completing this lesson, you should be able to do the following: • Distinguish between implicit and explicit cursors • Discuss the reasons for using explicit cursors • Declare and control explicit cursors • Use simple loops and cursor FOR loops to fetch data • Declare and use cursors with parameters • Lock rows with the FOR UPDATE clause • Reference the current row with the WHERE CURRENT OF clause
  • 140. Copyright © 2007, Oracle. All rights reserved. 7 - 175 Cursors Every SQL statement executed by the Oracle server has an associated individual cursor: • Implicit cursors: Declared and managed by PL/SQL for all DML and PL/SQL SELECT statements • Explicit cursors: Declared and managed by the programmer
  • 141. Copyright © 2007, Oracle. All rights reserved. 7 - 176 Explicit Cursor Operations Active set Table 100 King AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP . . . . . . . . . 139 Seo ST_CLERK 140 Patel ST_CLERK . . .
  • 142. Copyright © 2007, Oracle. All rights reserved. 7 - 177 Controlling Explicit Cursors • Load the current row into variables. FETCH • Test for existing rows. EMPTY? • Return to FETCH if rows are found. No • Release the active set. CLOSE Yes • Create a named SQL area. DECLARE • Identify the active set. OPEN
  • 143. Copyright © 2007, Oracle. All rights reserved. 7 - 178 Controlling Explicit Cursors Fetch a row. Close the cursor. Cursor pointer Open the cursor. 1 2 3 Cursor pointer Cursor pointer
  • 144. Copyright © 2007, Oracle. All rights reserved. 7 - 179 Declaring the Cursor Syntax: Examples: CURSOR cursor_name IS select_statement; DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; DECLARE v_locid NUMBER:= 1700; CURSOR c_dept_cursor IS SELECT * FROM departments WHERE location_id = v_locid; ...
  • 145. Copyright © 2007, Oracle. All rights reserved. 7 - 181 Opening the Cursor DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; ... BEGIN OPEN c_emp_cursor;
  • 146. Copyright © 2007, Oracle. All rights reserved. 7 - 182 Fetching Data from the Cursor DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; v_empno employees.employee_id%TYPE; v_lname employees.last_name%TYPE; BEGIN OPEN c_emp_cursor; FETCH c_emp_cursor INTO v_empno, v_lname; DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname); END; /
  • 147. Copyright © 2007, Oracle. All rights reserved. 7 - 184 Fetching Data from the Cursor DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; v_empno employees.employee_id%TYPE; v_lname employees.last_name%TYPE; BEGIN OPEN c_emp_cursor; LOOP FETCH c_emp_cursor INTO v_empno, v_lname; EXIT WHEN c_emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname); END LOOP; END; /
  • 148. Copyright © 2007, Oracle. All rights reserved. 7 - 185 Closing the Cursor ... LOOP FETCH c_emp_cursor INTO empno, lname; EXIT WHEN c_emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname); END LOOP; CLOSE c_emp_cursor; END; /
  • 149. Copyright © 2007, Oracle. All rights reserved. 7 - 186 Cursors and Records Process the rows of the active set by fetching values into a PL/SQL record. DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; v_emp_record c_emp_cursor%ROWTYPE; BEGIN OPEN c_emp_cursor; LOOP FETCH c_emp_cursor INTO v_emp_record; EXIT WHEN c_emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( v_emp_record.employee_id ||' '||v_emp_record.last_name); END LOOP; CLOSE c_emp_cursor; END;
  • 150. Copyright © 2007, Oracle. All rights reserved. 7 - 187 Cursor FOR Loops Syntax: • The cursor FOR loop is a shortcut to process explicit cursors. • Implicit open, fetch, exit, and close occur. • The record is implicitly declared. FOR record_name IN cursor_name LOOP statement1; statement2; . . . END LOOP;
  • 151. Copyright © 2007, Oracle. All rights reserved. 7 - 188 Cursor FOR Loops DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; BEGIN FOR emp_record IN c_emp_cursor LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' ' ||emp_record.last_name); END LOOP; END; /
  • 152. Copyright © 2007, Oracle. All rights reserved. 7 - 189 Explicit Cursor Attributes Use explicit cursor attributes to obtain status information about a cursor. Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far
  • 153. Copyright © 2007, Oracle. All rights reserved. 7 - 190 %ISOPEN Attribute • Fetch rows only when the cursor is open. • Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Example: IF NOT c_emp_cursor%ISOPEN THEN OPEN c_emp_cursor; END IF; LOOP FETCH c_emp_cursor...
  • 154. Copyright © 2007, Oracle. All rights reserved. 7 - 191 %ROWCOUNT and %NOTFOUND: Example DECLARE CURSOR c_emp_cursor IS SELECT employee_id, last_name FROM employees; v_emp_record c_emp_cursor%ROWTYPE; BEGIN OPEN c_emp_cursor; LOOP FETCH c_emp_cursor INTO v_emp_record; EXIT WHEN c_emp_cursor%ROWCOUNT > 10 OR c_emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( v_emp_record.employee_id ||' '||v_emp_record.last_name); END LOOP; CLOSE c_emp_cursor; END ; /
  • 155. Copyright © 2007, Oracle. All rights reserved. 7 - 192 Cursor FOR Loops Using Subqueries There is no need to declare the cursor. Example: BEGIN FOR emp_record IN (SELECT employee_id, last_name FROM employees WHERE department_id =30) LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' '||emp_record.last_name); END LOOP; END; /
  • 156. Copyright © 2007, Oracle. All rights reserved. 7 - 193 Cursors with Parameters Syntax: • Pass parameter values to a cursor when the cursor is opened and the query is executed. • Open an explicit cursor several times with a different active set each time. CURSOR cursor_name [(parameter_name datatype, ...)] IS select_statement; OPEN cursor_name(parameter_value,.....) ;
  • 157. Copyright © 2007, Oracle. All rights reserved. 7 - 194 Cursors with Parameters DECLARE CURSOR c_emp_cursor (deptno NUMBER) IS SELECT employee_id, last_name FROM employees WHERE department_id = deptno; ... BEGIN OPEN c_emp_cursor (10); ... CLOSE c_emp_cursor; OPEN c_emp_cursor (20); ...
  • 158. Copyright © 2007, Oracle. All rights reserved. 7 - 195 FOR UPDATE Clause Syntax: • Use explicit locking to deny access to other sessions for the duration of a transaction. • Lock the rows before the update or delete. SELECT ... FROM ... FOR UPDATE [OF column_reference][NOWAIT | WAIT n];
  • 159. Copyright © 2007, Oracle. All rights reserved. 7 - 197 WHERE CURRENT OF Clause Syntax: • Use cursors to update or delete the current row. • Include the FOR UPDATE clause in the cursor query to lock the rows first. • Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor. WHERE CURRENT OF cursor ; UPDATE employees SET salary = ... WHERE CURRENT OF c_emp_cursor;
  • 160. Copyright © 2007, Oracle. All rights reserved. 7 - 198 Cursors with Subqueries Example: DECLARE CURSOR my_cursor IS SELECT t1.department_id, t1.department_name, t2.staff FROM departments t1, (SELECT department_id, COUNT(*) AS staff FROM employees GROUP BY department_id) t2 WHERE t1.department_id = t2.department_id AND t2.staff >= 3; ...
  • 161. Copyright © 2007, Oracle. All rights reserved. 7 - 199 Summary In this lesson, you should have learned how to: • Distinguish cursor types: – Implicit cursors are used for all DML statements and single-row queries. – Explicit cursors are used for queries of zero, one, or more rows. • Create and handle explicit cursors • Use simple loops and cursor FOR loops to handle multiple rows in the cursors • Evaluate the cursor status by using the cursor attributes • Use the FOR UPDATE and WHERE CURRENT OF clauses to update or delete the current fetched row
  • 162. Copyright © 2007, Oracle. All rights reserved. 7 - 200 Practice 7: Overview This practice covers the following topics: • Declaring and using explicit cursors to query rows of a table • Using a cursor FOR loop • Applying cursor attributes to test the cursor status • Declaring and using cursors with parameters • Using the FOR UPDATE and WHERE CURRENT OF clauses
  • 163. Copyright © 2007, Oracle. All rights reserved. Handling Exceptions
  • 164. Copyright © 2007, Oracle. All rights reserved. 8 - 205 Objectives After completing this lesson, you should be able to do the following: • Define PL/SQL exceptions • Recognize unhandled exceptions • List and use different types of PL/SQL exception handlers • Trap unanticipated errors • Describe the effect of exception propagation in nested blocks • Customize PL/SQL exception messages
  • 165. Copyright © 2007, Oracle. All rights reserved. 8 - 206 Example of an Exception DECLARE v_lname VARCHAR2(15); BEGIN SELECT last_name INTO v_lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is :' ||v_lname); END;
  • 166. Copyright © 2007, Oracle. All rights reserved. 8 - 207 Example of an Exception DECLARE v_lname VARCHAR2(15); BEGIN SELECT last_name INTO v_lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is :' ||v_lname); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE (' Your select statement retrieved multiple rows. Consider using a cursor.'); END; /
  • 167. Copyright © 2007, Oracle. All rights reserved. 8 - 208 Handling Exceptions with PL/SQL • An exception is a PL/SQL error that is raised during program execution. • An exception can be raised: – Implicitly by the Oracle server – Explicitly by the program • An exception can be handled: – By trapping it with a handler – By propagating it to the calling environment
  • 168. Copyright © 2007, Oracle. All rights reserved. 8 - 209 Handling Exceptions Exception is raised. Is the exception trapped? Yes Execute statements in the EXCEPTION section. Terminate gracefully. No Terminate abruptly. Propagate the exception.
  • 169. Copyright © 2007, Oracle. All rights reserved. 8 - 210 Exception Types • Predefined Oracle server • Non-predefined Oracle server • User-defined }Implicitly raised Explicitly raised
  • 170. Copyright © 2007, Oracle. All rights reserved. 8 - 211 Trapping Exceptions Syntax: EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1; statement2; . . . [WHEN exception3 [OR exception4 . . .] THEN statement1; statement2; . . .] [WHEN OTHERS THEN statement1; statement2; . . .]
  • 171. Copyright © 2007, Oracle. All rights reserved. 8 - 213 Guidelines for Trapping Exceptions • The EXCEPTION keyword starts the exception-handling section. • Several exception handlers are allowed. • Only one handler is processed before leaving the block. • WHEN OTHERS is the last clause.
  • 172. Copyright © 2007, Oracle. All rights reserved. 8 - 214 Trapping Predefined Oracle Server Errors • Reference the predefined name in the exception- handling routine. • Sample predefined exceptions: – NO_DATA_FOUND – TOO_MANY_ROWS – INVALID_CURSOR – ZERO_DIVIDE – DUP_VAL_ON_INDEX
  • 173. Copyright © 2007, Oracle. All rights reserved. 8 - 217 Trapping Non-Predefined Oracle Server Errors Declarative section Declare Name the exception. Use PRAGMA EXCEPTION_INIT. EXCEPTION section Handle the raised exception. Associate Reference
  • 174. Copyright © 2007, Oracle. All rights reserved. 8 - 218 DECLARE e_insert_excep EXCEPTION; PRAGMA EXCEPTION_INIT(e_insert_excep, -01400); BEGIN INSERT INTO departments (department_id, department_name) VALUES (280, NULL); EXCEPTION WHEN e_insert_excep THEN DBMS_OUTPUT.PUT_LINE('INSERT OPERATION FAILED'); DBMS_OUTPUT.PUT_LINE(SQLERRM); END; / Non-Predefined Error To trap Oracle server error number –01400 (“cannot insert NULL”): 1 2 3
  • 175. Copyright © 2007, Oracle. All rights reserved. 8 - 219 Functions for Trapping Exceptions • SQLCODE: Returns the numeric value for the error code • SQLERRM: Returns the message associated with the error number
  • 176. Copyright © 2007, Oracle. All rights reserved. 8 - 220 Functions for Trapping Exceptions Example DECLARE error_code NUMBER; error_message VARCHAR2(255); BEGIN ... EXCEPTION ... WHEN OTHERS THEN ROLLBACK; error_code := SQLCODE ; error_message := SQLERRM ; INSERT INTO errors (e_user, e_date, error_code, error_message) VALUES(USER,SYSDATE,error_code, error_message); END; /
  • 177. Copyright © 2007, Oracle. All rights reserved. 8 - 221 Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception by using the RAISE statement. Exception-handling section Handle the raised exception. Raise Reference Declare
  • 178. Copyright © 2007, Oracle. All rights reserved. 8 - 222 Trapping User-Defined Exceptions DECLARE v_deptno NUMBER := 500; v_name VARCHAR2(20) := 'Testing'; e_invalid_department EXCEPTION; BEGIN UPDATE departments SET department_name = v_name WHERE department_id = v_deptno; IF SQL % NOTFOUND THEN RAISE e_invalid_department; END IF; COMMIT; EXCEPTION WHEN e_invalid_department THEN DBMS_OUTPUT.PUT_LINE('No such department id.'); END; / 1 2 3
  • 179. Copyright © 2007, Oracle. All rights reserved. 8 - 223 Propagating Exceptions in a Subblock DECLARE . . . e_no_rows exception; e_integrity exception; PRAGMA EXCEPTION_INIT (e_integrity, -2292); BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE e_no_rows; END IF; END; END LOOP; EXCEPTION WHEN e_integrity THEN ... WHEN e_no_rows THEN ... END; / Subblocks can handle an exception or pass the exception to the enclosing block.
  • 180. Copyright © 2007, Oracle. All rights reserved. 8 - 224 RAISE_APPLICATION_ERROR Procedure Syntax: • You can use this procedure to issue user-defined error messages from stored subprograms. • You can report errors to your application and avoid returning unhandled exceptions. raise_application_error (error_number, message[, {TRUE | FALSE}]);
  • 181. Copyright © 2007, Oracle. All rights reserved. 8 - 225 RAISE_APPLICATION_ERROR Procedure • Used in two different places: – Executable section – Exception section • Returns error conditions to the user in a manner consistent with other Oracle server errors
  • 182. Copyright © 2007, Oracle. All rights reserved. 8 - 226 RAISE_APPLICATION_ERROR Procedure Executable section: Exception section: BEGIN ... DELETE FROM employees WHERE manager_id = v_mgr; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202, 'This is not a valid manager'); END IF; ... ... EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20201, 'Manager is not a valid employee.'); END; /
  • 183. Copyright © 2007, Oracle. All rights reserved. 8 - 227 Summary In this lesson, you should have learned how to: • Define PL/SQL exceptions • Add an EXCEPTION section to the PL/SQL block to deal with exceptions at run time • Handle different types of exceptions: – Predefined exceptions – Non-predefined exceptions – User-defined exceptions • Propagate exceptions in nested blocks and call applications
  • 184. Copyright © 2007, Oracle. All rights reserved. 8 - 228 Practice 8: Overview This practice covers the following topics: • Handling named exceptions • Creating and invoking user-defined exceptions
  • 185. Copyright © 2007, Oracle. All rights reserved. Creating Stored Procedures and Functions
  • 186. Copyright © 2007, Oracle. All rights reserved. 9 - 232 Objectives After completing this lesson, you should be able to do the following: • Differentiate between anonymous blocks and subprograms • Create a simple procedure and invoke it from an anonymous block • Create a simple function • Create a simple function that accepts a parameter • Differentiate between procedures and functions
  • 187. Copyright © 2007, Oracle. All rights reserved. 9 - 233 Procedures and Functions • Are named PL/SQL blocks • Are called PL/SQL subprograms • Have block structures similar to anonymous blocks: – Optional declarative section (without the DECLARE keyword) – Mandatory executable section – Optional section to handle exceptions
  • 188. Copyright © 2007, Oracle. All rights reserved. 9 - 234 Differences Between Anonymous Blocks and Subprograms Anonymous Blocks Subprograms Unnamed PL/SQL blocks Named PL/SQL blocks Compiled every time Compiled only once Not stored in the database Stored in the database Cannot be invoked by other applications Named and, therefore, can be invoked by other applications Do not return values Subprograms called functions must return values. Cannot take parameters Can take parameters
  • 189. Copyright © 2007, Oracle. All rights reserved. 9 - 235 Procedure: Syntax CREATE [OR REPLACE] PROCEDURE procedure_name [(argument1 [mode1] datatype1, argument2 [mode2] datatype2, . . .)] IS|AS procedure_body;
  • 190. Copyright © 2007, Oracle. All rights reserved. 9 - 236 Procedure: Example ... CREATE TABLE dept AS SELECT * FROM departments; CREATE PROCEDURE add_dept IS v_dept_id dept.department_id%TYPE; v_dept_name dept.department_name%TYPE; BEGIN v_dept_id:=280; v_dept_name:='ST-Curriculum'; INSERT INTO dept(department_id,department_name) VALUES(v_dept_id,v_dept_name); DBMS_OUTPUT.PUT_LINE(' Inserted '|| SQL%ROWCOUNT ||' row '); END;
  • 191. Copyright © 2007, Oracle. All rights reserved. 9 - 238 Invoking the Procedure BEGIN add_dept; END; / SELECT department_id, department_name FROM dept WHERE department_id=280;
  • 192. Copyright © 2007, Oracle. All rights reserved. 9 - 239 Function: Syntax CREATE [OR REPLACE] FUNCTION function_name [(argument1 [mode1] datatype1, argument2 [mode2] datatype2, . . .)] RETURN datatype IS|AS function_body;
  • 193. Copyright © 2007, Oracle. All rights reserved. 9 - 240 Function: Example CREATE FUNCTION check_sal RETURN Boolean IS v_dept_id employees.department_id%TYPE; v_empno employees.employee_id%TYPE; v_sal employees.salary%TYPE; v_avg_sal employees.salary%TYPE; BEGIN v_empno:=205; SELECT salary,department_id INTO v_sal,v_dept_id FROM employees WHERE employee_id= v_empno; SELECT avg(salary) INTO v_avg_sal FROM employees WHERE department_id=v_dept_id; IF v_sal > v_avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END;
  • 194. Copyright © 2007, Oracle. All rights reserved. 9 - 241 Invoking the Function BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; END; /
  • 195. Copyright © 2007, Oracle. All rights reserved. 9 - 242 Passing a Parameter to the Function DROP FUNCTION check_sal; CREATE FUNCTION check_sal(p_empno employees.employee_id%TYPE) RETURN Boolean IS v_dept_id employees.department_id%TYPE; v_sal employees.salary%TYPE; v_avg_sal employees.salary%TYPE; BEGIN SELECT salary,department_id INTO v_sal,v_dept_id FROM employees WHERE employee_id=p_empno; SELECT avg(salary) INTO v_avg_sal FROM employees WHERE department_id=v_dept_id; IF v_sal > v_avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION ...
  • 196. Copyright © 2007, Oracle. All rights reserved. 9 - 243 Invoking the Function with a Parameter BEGIN DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205'); IF (check_sal(205) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(205)) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; DBMS_OUTPUT.PUT_LINE('Checking for employee with id 70'); IF (check_sal(70) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(70)) THEN ... END IF; END; /
  • 197. Copyright © 2007, Oracle. All rights reserved. 9 - 244 Summary In this lesson, you should have learned how to: • Create a simple procedure • Invoke the procedure from an anonymous block • Create a simple function • Create a simple function that accepts parameters • Invoke the function from an anonymous block
  • 198. Copyright © 2007, Oracle. All rights reserved. 9 - 245 Practice 9: Overview This practice covers the following topics: • Converting an existing anonymous block to a procedure • Modifying the procedure to accept a parameter • Writing an anonymous block to invoke the procedure