You are on page 1of 13

LAB 03

PL/SQL Variables and Operators


This lab will introduce you to the basic concepts of PL/SQL variables and operators.

Objectives:
By the end of this lab, students will be able to use PL/SQL variables and operators.

Pre-Requisite:
Knowledge of basic SQL commands.

PL/SQL Variables

A variable is a meaningful name of a temporary storage location that supports a


specific data type in a program.
First, you need to declare a variable in declaration section before using it.
The variable name must be meaningful, and it must be less than 31 characters.
The variable name must begin with an ASCII character. It can be either lowercase or
uppercase.
Note that PL/SQL is case-insensitive, which means that v_data and V_DATA refers to
the same variable.

Variable Declaration Syntax


variable_name datatype [NOT NULL := value ];

variable_name is the name of the variable.

datatype is a valid PL/SQL datatype.

NOT NULL is an optional specification on the variable.

value or DEFAULT value is also an optional specification, where you can initialize a
variable.

Each variable declaration is a separate statement and must be terminated by a semicolon.

Variable Declaration Examples


Some valid variable declarations along with their definition are shown below:
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);

Initializing PL/SQL Variables


Whenever you declare a variable; the value assigned to it by PL/SQL is NULL by default. If you want
to assign a value other than NULL, then you may use the methods shown below:

counter binary_integer NOT NULL := 0;


greetings varchar2(20) DEFAULT 'Have a Good Day';

Note that, when you use NOT NULL constraint, then you must explicitly assign an initial value to the
variable. Also note that you may either initialize variables in Declaration section or in Execution
section of PL/SQL block.

PL/SQL variable anchors


One of the most common tasks in PL/SQL is to select values from table columns into variables.
Suppose that, data type of a column changes in a table; then you have to modify the PL/SQL
program to make it compatible with the table that you are using.
In order to handle this problem, PL/SQL provides a very useful feature called variable anchor.
Variable anchor refers to the use of %TYPE keyword. Now, if the data type of any column changes
in a table, PL/SQL will automatically modify the data type of variables in PL/SQL program. You just
have to declare variable with the %TYPE keyword.
Consider the following employees table.

DECLARE
v_first_name EMPLOYEES.FIRST_NAME%TYPE;
v_last_name EMPLOYEES.LAST_NAME%TYPE;
n_employee_id EMPLOYEES.EMPLOYEE_ID%TYPE;
d_hire_date EMPLOYEES.HIRE_DATE%TYPE;
BEGIN
NULL;
END;
/

In the above declaration section, the variable v_frst_name has the data type as first_name (column
name) in employees table. If the data type of first_name changes in table, then PL/SQL will
automatically update the data type of v_first_name in the program.

PL/SQL Variable Assignment


The following example shows how to assign values to variables

SET SERVEROUTPUT ON
DECLARE
v_first_name EMPLOYEES.FIRST_NAME%TYPE;
v_last_name EMPLOYEES.LAST_NAME%TYPE;
n_employee_id EMPLOYEES.EMPLOYEE_ID%TYPE;
d_hire_date EMPLOYEES.HIRE_DATE%TYPE;
BEGIN
SELECT employee_id,
first_name,
last_name,
hire_date
INTO
n_employee_id,
v_first_name,
v_last_name,
d_hire_date
FROM employees
WHERE employee_id = 200;
DBMS_OUTPUT.PUT_LINE(v_first_name);
DBMS_OUTPUT.PUT_LINE(v_last_name);
DBMS_OUTPUT.PUT_LINE(d_hire_date);
END;
/

Scope of Variables in PL/SQL


Nesting of blocks is allowed in PL/SQL. So, there are typically two types of blocks in PL/SQL, which
are outer block and inner blocks. There can only be one outer block which is also the main block,
and there can be one or more inner blocks. PL/SQL allows two kinds of variable scopes which are:
1. Global Variable Scope
The variables which are declared in the main block or outer block of the PL/SQL program are
called global variables. These variables can be accessed in all inner blocks.
2. Local Variable Scope
The variables which are declared in the inner blocks of the PL/SQL program are called local
variables. They can only be accessed in the block in which they were declared.

Variable Scope Example

DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/

Executing the above code produces the following result.

Outer Variable num1: 95


Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185
PL/SQL procedure successfully completed.

Variable Scope Identifier


If variables in inner block and outer block have same names, and you want to access outer block
variable from inner block; then you must use OUTER keyword in inner block to access the outer
block variable. It is called global qualified scope. The following example shows how to use OUTER
keyword in a PL/SQL program.

DECLARE
num number := 10;
BEGIN
DECLARE
num number := 10;
BEGIN
IF num = OUTER.num THEN
DBMS_OUTPUT.PUT_LINE('Both have same value');
ELSE
DBMS_OUTPUT.PUT_LINE('Different value');
END IF;
END; -- End of scope to access num variable
END;
/

Example of PL/SQL function:


CREATE OR REPLACE FUNCTION squareme(thenum number)
RETURN NUMBER IS
BEGIN
RETURN thenum * thenum;
END squareme;
/
BEGIN
DBMS_OUTPUT.PUT_LINE('9 squared is ' || squareme(9) );
END;
/

PL/SQL Operators

PL/SQL provides the following operators.

Arithmetic operators

Relational operators

Comparison operators

Logical operators

String operators

Arithmetic operators
The following table shows all the arithmetic operators that can be used in PL/SQL programs.

Operator

Description

Example

Adds two operands

A + B will
give 15

Subtracts second operand from the first

A - B will
give 5

Multiplies both operands

A * B will
give 50

Divides numerator by de-numerator

A / B will
give 2

**

Exponentiation operator, raises one operand to the power of other

A ** B will
give
100000

Relational Operators
Relational operators are used to compare variables and they always return a Boolean value. The
following table shows relational operators that can be used in PL/SQL programs.

Operator

Description

Example

Checks if the values of two operands are


equal or not, if yes then condition becomes
true.

(A = B)
is not
true.

Checks if the values of two operands


are equal or not, if values are not
equal then condition becomes true.

(A != B) is true.

>

Checks if the value of left operand is greater


than the value of right operand, if yes then
condition becomes true.

(A > B)
is not
true.

<

Checks if the value of left operand is less


than the value of right operand, if yes then
condition becomes true.

(A < B)
is true.

>=

Checks if the value of left operand is greater


than or equal to the value of right operand,
if yes then condition becomes true.

(A >= B)
is not
true.

<=

Checks if the value of left operand is less


than or equal to the value of right operand,
if yes then condition becomes true.

(A <= B)
is true.

Comparison Operators
These operators are used to compare expressions. The following table shows comparison operators
that can be used in PL/SQL programs.

Operator

Description

Example

LIKE

The LIKE operator compares a character, string, or CLOB value to a pattern and
returns TRUE if the value matches the pattern and FALSE if it does not.

If 'Zara Ali'
like 'Z% A_i'
returns a
Boolean true,
whereas,
'Nuha Ali' like
'Z% A_i'
returns a
Boolean false.

BETWEEN

The BETWEEN operator tests whether a value lies in a specified range. x


BETWEEN a AND b means that x >= a and x <= b.

If x = 10
then, x
between 5
and 20
returns true, x
between 5
and 10
returns true,
but x between
11 and 20
returns false.

IN

The IN operator tests set membership. x IN (set) means that x is equal to any
member of set.

If x = 'm'
then, x in ('a',
'b', 'c')
returns
boolean false
but x in ('m',
'n', 'o')
returns
Boolean true.

IS NULL

The IS NULL operator returns the BOOLEAN value TRUE if its operand is NULL or
FALSE if it is not NULL. Comparisons involving NULL values always yield NULL.

If x = 'm',
then 'x is null'
returns
Boolean false.

Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators work on
Boolean operands and produces Boolean results. Assume variable A holds true and variable B holds
false, then:

Operator

Description

Example

and

Called logical AND operator. If both the operands are true then
condition becomes true.

(A and
B) is
false.

or

Called logical OR Operator. If any of the two operands is true then


condition becomes true.

(A or B)
is true.

not

Called logical NOT Operator. Used to reverse the logical state of its
operand. If a condition is true then Logical NOT operator will make it
false.

not (A
and B) is

Operator Precedence in PL/SQL


The following table shows you the precedence of operators. The operators with higher precedence
appear at the top of table, and those with lower precedence appear at the bottom of table.

Operator

Operation

**

Exponentiation

+, -

identity, negation

*, /

multiplication, division

+, -, ||

addition, subtraction, concatenation

Comparison

NOT

logical negation

AND

Conjunction

OR

Inclusion

Comments in PL/SQL
Comments in PL/SQL are used either with /* */ or -The /* and */ are used in tandem and can be used over multiple lines. They cannot be nested.
Everything between /* and */ is ignored.
The -- is used at the end of a line. Everything after the -- is ignored up to the carriage return.

Lab Tasks

Create the following table.


Student_Result
Student_i

First_nam

Last_Nam

Email

Departme

DOB

d
200121

e
Ali

e
Haider

200122

Rizwan

Pasha

200123

Ibrahim

Ali

200124

Khawar

Hayyat

200125

Ali

Azmat

Ali_haider@gmail.com
Rizwan_pasha@hotmai
l.com
Ibrahim123@yahoo.co
m
Khawar321@yahoo.co
m
Ali_azmat@gmail.com

nt
CS
EE
Geology
CS
EE

01-Jun1993
06-July1994
14-Aug1994
25-Dec1994
9-Sep1994

Task 01:
Declare two variables and store emails of students in them. The
student ids for those students should be 200121 and 200122
respectively.
Task 02:
Create a PL/SQL block to find the age of the student whose student id
is 200123. (Hint: Use SYSDATE, DATE keyword, and Extract function
respectively.)
Task 03:
Create a PL/SQL block to delete the record of student whose id is
200125.
Task 04:
Write a PL/SQL block to update the email of student whose student id is
200121. Also display the previous and updated emails of student.
Task 05:
Write a function to find result of the following formula.
a2 +b 2+2 ab

Where a and b should be passed as parameters to the function.

INCLUDE Irvine32.inc
.data
a byte 0
ar2 dword 10 DUP(0)
.code
main PROC
mov eax , 0
mov esi , offset ar2
mov ecx, 10
Output:
call readint
mov a,ah
mov ah,a
mov [esi],ah
add esi,1
call writedec
call crlf
Loop Output
Exit
Main ENDP
END main