Types of Variables PL/SQL variables

Introduction to PL/SQL
Copyright © 2006, Oracle. All rights reserved.
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
• Use iSQL*Plus as a development environment for
PL/SQL
• Output messages in PL/SQL
1-2
Copyright © 2006, Oracle. All rights reserved.
What Is 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
1-3
Copyright © 2006, Oracle. All rights reserved.
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 types
– Control structures such as conditional statements
and loops
– Reusable program units that are written once and
executed many times
1-4
Copyright © 2006, Oracle. All rights reserved.
PL/SQL Environment
PL/SQL engine
procedural
PL/SQL
Block
SQL
Procedural
Statement
Executor
SQL Statement
Executor
Oracle Database Server
1-5
Copyright © 2006, Oracle. All rights reserved.
Benefits of PL/SQL
•
•
Integration of procedural constructs with SQL
Improved performance
SQL 1
SQL 2
…
SQL
IF...THEN
SQL
ELSE
SQL
END IF;
SQL
1-6
Copyright © 2006, Oracle. All rights reserved.
Benefits of PL/SQL
•
•
•
•
1-7
Modularized program development
Integration with Oracle tools
Portability
Exception handling
Copyright © 2006, Oracle. All rights reserved.
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
•
1-9
END; (mandatory)
Copyright © 2006, Oracle. All rights reserved.
Block Types
Anonymous
1-11
Procedure
Function
[DECLARE]
PROCEDURE name
IS
BEGIN
--statements
BEGIN
--statements
[EXCEPTION]
[EXCEPTION]
FUNCTION name
RETURN datatype
IS
BEGIN
--statements
RETURN value;
[EXCEPTION]
END;
END;
END;
Copyright © 2006, Oracle. All rights reserved.
PL/SQL Programming Environments
1-13
Copyright © 2006, Oracle. All rights reserved.
PL/SQL Programming Environments
iSQL*Plus
1-14
Copyright © 2006, Oracle. All rights reserved.
PL/SQL Programming Environments
1-15
Copyright © 2006, Oracle. All rights reserved.
iSQL*Plus Architecture
1-16
Copyright © 2006, Oracle. All rights reserved.
Create an Anonymous Block
Type the anonymous block in the SQL*Plus
workspace:
declare
name varchar2(10) ;
begin
select last_name into name
from employees
where department_id=50;
end;
/
1-17
Copyright © 2006, Oracle. All rights reserved.
Execute an Anonymous Block
-type / at SQL*PLUS prompt
PL\SQL procedure successfully completed.
1-18
Copyright © 2006, Oracle. All rights reserved.
Test the Output of a PL/SQL Block
•
Enable output in SQL*Plus with the following
command:
SET SERVEROUTPUT ON
•
Use a predefined Oracle package and its
procedure:
– DBMS_OUTPUT.PUT_LINE
SET SERVEROUTPUT ON
…
DBMS_OUTPUT.PUT_LINE(' The First Name of the
Employee is ' || f_name);
…
1-19
Copyright © 2006, Oracle. All rights reserved.
Test the Output of a PL/SQL Block
1-20
Copyright © 2006, Oracle. All rights reserved.
Summary
In this lesson, you should have learned how to:
• Integrate SQL statements with PL/SQL program
constructs
• Identify the benefits of PL/SQL
• Differentiate different PL/SQL block types
• Use iSQL*Plus as the programming environment
for PL/SQL
• Output messages in PL/SQL
1-21
Copyright © 2006, Oracle. All rights reserved.
Declaring PL/SQL Variables
Copyright © 2006, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following:
• Identify 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
•
1-23
Declare, use, and print bind variables
Copyright © 2006, Oracle. All rights reserved.
Use of Variables
Variables can be used for:
• Temporary storage of data
• Manipulation of stored values
• Reusability
SELECT
first_name,
department_id
INTO
emp_fname,
emp_deptno
FROM …
1-24
Jennifer emp_fname
Copyright © 2006, Oracle. All rights reserved.
10 emp_deptno
Identifiers
Identifiers are used for:
• Naming a variable
• Providing conventions for variable names
– Must start with a letter
– Can include letters or numbers
– Can include special characters (such as dollar sign,
underscore, and pound sign)
– Must limit the length to 30 characters
– Must not be reserved words
1-25
Copyright © 2006, Oracle. All rights reserved.
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
1-26
Copyright © 2006, Oracle. All rights reserved.
Declaring and Initializing PL/SQL Variables
Syntax
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
Examples
DECLARE
emp_hiredate
emp_deptno
location
c_comm
1-27
DATE;
NUMBER(2) NOT NULL := 10;
VARCHAR2(13) := 'Atlanta';
CONSTANT NUMBER := 1400;
Copyright © 2006, Oracle. All rights reserved.
Declaring and Initializing PL/SQL Variables
1
2
1-28
SET SERVEROUTPUT ON
DECLARE
Myname VARCHAR2(20);
BEGIN
DBMS_OUTPUT.PUT_LINE('My name is: '||Myname);
Myname := 'John';
DBMS_OUTPUT.PUT_LINE('My name is: '||Myname);
END;
/
SET SERVEROUTPUT ON
DECLARE
Myname VARCHAR2(20):= 'John';
BEGIN
Myname := 'Steven';
DBMS_OUTPUT.PUT_LINE('My name is: '||Myname);
END;
/
Copyright © 2006, Oracle. All rights reserved.
Delimiters in String Literals
SET SERVEROUTPUT ON
DECLARE
event VARCHAR2(15);
BEGIN
event := q'!Father's day!';
DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is :
'||event);
event := q'[Mother's day]';
DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is :
'||event);
END;
/
1-29
Copyright © 2006, Oracle. All rights reserved.
Types of Variables
•
PL/SQL variables:
–
–
–
–
•
1-30
Scalar
Composite
Reference
Large object (LOB)
Non-PL/SQL variables: Bind variables
Copyright © 2006, Oracle. All rights reserved.
Types of Variables
TRUE
25-JAN-01
The soul of the lazy man
desires, and he has nothing;
but the soul of the diligent
shall be made rich.
256120.08
1-31
Atlanta
Copyright © 2006, Oracle. All rights reserved.
Scalar Data Types
•
•
Hold a single value
Have no internal components
TRUE
25-JAN-01
The soul of the lazy man
desires, and he has nothing;
but the soul of the diligent
shall be made rich.
256120.08
1-34
Atlanta
Copyright © 2006, Oracle. All rights reserved.
Base Scalar Data Types
•
•
•
•
•
•
•
•
•
•
1-35
CHAR [(maximum_length)]
VARCHAR2 (maximum_length)
LONG
LONG RAW
NUMBER [(precision, scale)]
BINARY_INTEGER
PLS_INTEGER
BOOLEAN
BINARY_FLOAT
BINARY_DOUBLE
Copyright © 2006, Oracle. All rights reserved.
Base Scalar Data Types
•
•
•
•
•
•
1-36
DATE
TIMESTAMP
TIMESTAMP WITH TIME ZONE
TIMESTAMP WITH LOCAL TIME ZONE
INTERVAL YEAR TO MONTH
INTERVAL DAY TO SECOND
Copyright © 2006, Oracle. All rights reserved.
Declaring Scalar Variables
Examples
DECLARE
emp_job
count_loop
dept_total_sal
orderdate
c_tax_rate
valid
...
1-37
VARCHAR2(9);
BINARY_INTEGER := 0;
NUMBER(9,2) := 0;
DATE := SYSDATE + 7;
CONSTANT NUMBER(3,2) := 8.25;
BOOLEAN NOT NULL := TRUE;
Copyright © 2006, Oracle. All rights reserved.
%TYPE Attribute
The %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
1-38
Copyright © 2006, Oracle. All rights reserved.
Declaring Variables
with the %TYPE Attribute
Syntax
identifier
table.column_name%TYPE;
Examples
...
emp_lname
balance
min_balance
...
1-39
employees.last_name%TYPE;
NUMBER(7,2);
balance%TYPE := 1000;
Copyright © 2006, Oracle. All rights reserved.
Declaring Boolean Variables
•
•
•
•
1-40
Only the values TRUE, FALSE, and NULL 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 © 2006, Oracle. All rights reserved.
Bind Variables
Bind variables are:
• Created in the environment
• Also called host variables
• Created with the VARIABLE keyword
•
•
•
1-41
Used in SQL statements and PL/SQL blocks
Accessed even after the PL/SQL block is executed
Referenced with a preceding colon
Copyright © 2006, Oracle. All rights reserved.
Bind variables
Bind variables are used in SQL and PL/SQL statements
for holding data or result sets
There is no way to undefine or delete a bind variable in
a SQL*Plus session. However, bind variables are not
remembered when you exit SQL*Plus.
1-42
Copyright © 2006, Oracle. All rights reserved.
Printing Bind Variables
Example
VARIABLE emp_salary NUMBER
BEGIN
SELECT salary INTO :emp_salary
FROM employees WHERE employee_id = 178;
END;
/
PRINT emp_salary
SELECT first_name, last_name FROM employees
WHERE salary=:emp_salary;
1-43
Copyright © 2006, Oracle. All rights reserved.
Printing Bind Variables
Example
VARIABLE emp_salary NUMBER
SET AUTOPRINT ON
BEGIN
SELECT salary INTO :emp_salary
FROM employees WHERE employee_id = 178;
END;
/
1-44
Copyright © 2006, Oracle. All rights reserved.
Substitution Variables
•
•
•
Are used to get user input at run time
Are referenced within a PL/SQL block with a
preceding ampersand
Are used to avoid hard-coding values that can be
obtained at run time
VARIABLE emp_salary NUMBER
SET AUTOPRINT ON
DECLARE
empno NUMBER(6):=&empno;
BEGIN
SELECT salary INTO :emp_salary
FROM employees WHERE employee_id = empno;
END;
/
1-45
Copyright © 2006, Oracle. All rights reserved.
Substitution Variables
1
2
3
1-46
Copyright © 2006, Oracle. All rights reserved.
Prompt for Substitution Variables
SET VERIFY OFF
VARIABLE emp_salary NUMBER
ACCEPT empno PROMPT 'Please enter a valid employee
number: '
SET AUTOPRINT ON
DECLARE
empno NUMBER(6):= &empno;
BEGIN
SELECT salary INTO :emp_salary FROM employees
WHERE employee_id = empno;
END;
/
1-47
Copyright © 2006, Oracle. All rights reserved.
Using DEFINE for a User Variable
Example
SET VERIFY OFF
DEFINE lname= Urman
DECLARE
fname VARCHAR2(25);
BEGIN
SELECT first_name INTO fname FROM employees
WHERE last_name='&lname';
END;
/
1-48
Copyright © 2006, Oracle. All rights reserved.
Showing and Deleting Substitution Variables
-DEFINE
-DEFINE variable_name
-UNDEFINE
-UNDEFINE variable_name
1-49
Copyright © 2006, Oracle. All rights reserved.
Substitution variables
Substitution variable references are pre-processed and substituted
before the command is otherwise parsed and executed.
For each statement SQL*Plus will:
1. Loop for each "&" and "&&" variable reference
If the variable is defined
Replace the variable reference with the value
else
Prompt for a value
Replace the variable reference with the value
If the variable is prefixed with "&&" then define
(i.e. store) the variable for future use
2. Execute the statement
Step 1 happens inside the SQL*Plus client tool. SQL*Plus then sends the final
statement to the database engine where step 2 occurs
1-50
Copyright © 2006, Oracle. All rights reserved.
Substitution variables
It is not possible to repeatedly prompt in a PL/SQL
loop. This example prompts once and the entered
value is substituted in the script text. The resulting
script is then sent to the database engine for
execution. The same entered value is stored five times
in the table:
begin
for i in 1 .. 5 loop
insert into mytable values (&myv);
end loop;
end;
1-51
Copyright © 2006, Oracle. All rights reserved.
Composite Data Types
TRUE
23-DEC-98
PL/SQL table structure
1
2
3
4
SMITH
JONES
NANCY
TIM
ATLANTA
PL/SQL table structure
1
2
3
4
5000
2345
12
3456
NUMBER
VARCHAR2
PLS_INTEGER
1-52
PLS_INTEGER
Copyright © 2006, Oracle. All rights reserved.
LOB Data Type Variables
Book
(CLOB)
Photo
(BLOB)
Movie
(BFILE)
1-53
Copyright © 2006, Oracle. All rights reserved.
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
•
1-54
Use bind variables
Copyright © 2006, Oracle. All rights reserved.