PL SQL
PL SQL
Introduction
The basic construct in PL/SQL is a block. Blocks allow designers to combine logically
related (SQL-) statements into units. In a block, constants and variables can be declared,
and variables can be used to store query results. Statements in a PL/SQL block include SQL
statements, control structures (loops), condition statements (if-then-else), exception
handling, and calls of other PL/SQL blocks.
PL/SQL blocks that specify procedures and functions can be grouped into packages.
A package is similar to a module and has an interface and an implementation part. Oracle
o_ers several predefined packages, for example, input/output routines, file handling, job
scheduling etc.
1
• develop modular database application programs,
• reuse program code, and
• reduce the cost for maintaining and changing applications.
Structure of PL/SQL-Blocks
A PL/SQL block has an optional declare section, a part containing PL/SQL statements,
and an optional exception-handling part. Thus the structure of a PL/SQL looks as follows
(brackets [ ] enclose optional parts):
[<Block header>]
[declare
<Constants>
<Variables>
<Cursors>
<User defined exceptions>]
begin
<PL/SQL statements>
[exception
<Exception handling>]
end;
The block header specifies whether the PL/SQL block is a procedure, a function, or a
package. If no header is specified, the block is said to be an anonymous PL/SQL block. Each
PL/SQL block again builds a PL/SQL statement. Thus blocks can be nested like blocks in
conventional programming languages. The scope of declared variables (i.e., the part of the
program in which one can refer to the variable) is analogous to the scope of variables in
programming languages
such as C or Pascal.
Declarations
Constants, variables, cursors, and exceptions used in a PL/SQL block must be declared in the
declare section of that block. Variables and constants can be declared as follows:
2
Valid data types are SQL data types (see Section 1.1) and the data type boolean. Boolean
data may only be true, false, or null. The not null clause requires that the declared variable
must always have a value di_erent from null. <expression> is used to initialize a variable.
If no expression is specified, the value null is assigned to the variable. The clause constant
states that once a value has been assigned to the variable, the value cannot be changed
(thus the variable becomes a constant).
Example:
Declare hire date date; /* implicit initialization with null */
job title varchar2(80) := ’Salesman’;
emp found boolean; /* implicit initialization with null */
salary incr constant number(3,2) := 1.5; /* constant */
...
begin
...
end;
Instead of specifying a data type, one can also refer to the data type of a table column (so-
called anchored declaration). For example, EMP.Empno%TYPE refers to the data type of the
column Empno in the relation EMP. Instead of a single variable, a record can be declared
that can store a complete tuple from a given table (or query result). For example, the data
type DEPT%ROWTYPE specifies a record suitable to store all attribute values of a complete
row from the table DEPT. Such records are typically used in combination with a cursor. A
field in a record can be accessed using <record name>.<column name>, for example,
DEPT.Deptno.
3
DATATYPES
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a
subtype called INTEGER. You can use the subtypes in your PL/SQL program to make the
data types compatible with data types in other programs while embedding the PL/SQL code
in another program, such as a Java program.
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types –
NUMBER(prec, scale)
1 Fixed-point or floating-point number with absolute value in range 1E-130 to
(but not including) 1.0E126. A NUMBER variable can also represent 0
FLOAT
2 ANSI and IBM specific floating-point type with maximum precision of 126
binary digits (approximately 38 decimal digits)
DATE
3
DATE datatype stores valid date time format with fixed length.
INTEGER
4
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
4
PL/SQL procedure successfully completed
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
S.No Data Type & Description
CHAR
1
Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2
2
Variable-length character string with maximum size of 32,767 bytes
RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL
ROWID
4
Physical row identifier, the address of a row in an ordinary table
5
PL/SQL Operator Precedence
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE,
BETWEEN, IN.
Show Examples
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
== comparison
AND conjunction
6
OR inclusion
In PL/SQL there are three types of conditional control statements: IF, ELSIF and CASE
IF – THEN Statement
This is the most basic kind of a conditional control and has the following structure
If Condition Then
Statement 1;
….
Statement 2;
End If;
The reserved word IF marks the beginning of the IF statement.
Example:
Q) Write a PL/SQL block to swap two numbers when the first number is greater
than second number ?
SQL> declare
a number(10) := &a;
b number(10) := &b;
c number(10);
begin
dbms_output.put_line('a value ='||a||' b value ='||b);
if a>b then
c := a;
a := b;
b := c;
end if;
dbms_output.put_line('a value ='||a||' b value ='||b);
end;
/
7
OUTPUT:
Enter value for a: 20
old 2: a number(10) := &a;
new 2: a number(10) := 20;
Enter value for b: 10
old 3: b number(10) := &b;
new 3: b number(10) := 10;
a value =20 b value =10
a value =10 b value =20
IF – THEN – ELSE
This statement enables you to specify two groups of statements One group of
statements is executed when the condition evaluates to TRUE and the other group of
statements is executed when the condition evaluates to FALSE.
If Condition Then
Statement 1;
ELSE
Statement 2;
End If;
Statement 3;
Example:
Q) Write a PL/SQL block to test whether the given number is odd or even
SQL> declare
a number(10) := &a;
begin
if mod(a,2)=0 then
dbms_output.put_line('a value is even');
else
dbms_output.put_line('a value is odd');
end if;
end;
/
8
a value is even
ELSIF Statement:
This statement has the following structure
If Condition 1 Then
Statement 1;
ELSIF Condition 2 Then
Statement 2;
ELSIF Condition 3 Then
Statement 3;
…
ELSE
Statement 4;
END IF;
Example:
Q)Write a PL/SQL block to find the grade of sailor for a given sid
10, 9, 8 – Grade A
7, 6, 5 – Grade B
other – Grade C
SQL> declare
2 a number(10) := &a;
c number(10);
begin
select rating into c from sailors where sid = a;
if c in (10,9,8) then
dbms_output.put_line('sailor '||a||' has grade A');
elsif c in (7,6,5) then
dbms_output.put_line('sailor '||a||' has grade B');
else
dbms_output.put_line('sailor '||a||' has grade C');
9
end if;
end;
/
Enter value for a: 22
old 2: a number(10) := &a;
new 2: a number(10) := 22;
sailor 22 has grade B
CASE SELECTOR
WHEN EXPRESSION 1 STATEMENT 1;
WHEN EXPRESSION 1 STATEMENT 1;
…..
WHEN EXPRESSION 1 STATEMENT 1;
ELSE STATEMENT N+1;
END CASE;
The reserved word CASE marks the beginning of the case statement. A selector is a value
that determines which WHEN clause should be executed.
Example:
Q7) Write a PL/SQL block to print the day name for a given date?
SQL> declare
a date := '&a';
b char(10);
begin
b := to_char(a,'D');
case b
when '1' then
dbms_output.put_line('today is sunday');
when '2' then
dbms_output.put_line('today is monday');
when '3' then
dbms_output.put_line('today is thuesday');
when '4' then
dbms_output.put_line('today is wednesday');
10
when '5' then
dbms_output.put_line('today is thrusday');
when '6' then
dbms_output.put_line('today is friday');
when '7' then
dbms_output.put_line('today is saturday');
end case;
end;
/
Enter value for a: 10-mar-09
old 2: a date := '&a';
new 2: a date := '10-mar-09';
today is thuesday
ITERATIVE CONTROL
In PL/SQL there are three types of loops : Simple LOOP, WHILE loops and Numeric FOR loop
A simple loop, as you can see from its name, is the most basic kind of loop and has the
following structure:
LOOP
STATEMENT 1;
STATEMENT 2;
…….
STATEMENT N;
END LOOP;
The reserved word LOOP marks the beginning of the simple loop. Statement 1 through N
are a sequence of statements that is executed repeatedly.
EXIT statement causes a loop to terminate when exit condition evaluates to TRUE.
LOOP
STATEMENT 1;
STATEMENT 2;
IF CONDITION THEN
EXITL;
11
END IF;
…….
STATEMENT N;
END LOOP;
Example:
Q8) Write a PL/SQL block to print number from 1 to 5 using loop statements
SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value'||a);
if a>5 then
exit;
end if;
end loop;
end;
/
a value1
a value2
a value3
a value4
a value5
a value6
Note: here numbers are printed 1 to 6 because this loop acts as do-while so it executes the
statements and then check the condition next.
LOOP
STATEMENT 1;
STATEMENT 2;
EXIT WHEN CONDITION;
…….
STATEMENT N;
END LOOP;
12
Q8) Write a PL/SQL block to print number from 1 to 5 using loop statements
SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value'||a);
exit when a>5 ;
end loop;
end;
/
a value1
a value2
a value3
a value4
a value5
a value6
WHILE LOOPS:
A while loop has the following structure
13
The reserved word WHILE marks the beginning of a loop construct. The word CONDITION is
the test condition of the loop that evaluates to TRUE or FALSE.
Example:
Q9) Write a PL/SQL block to print number from 1 to 5 using while loop statements
SQL> declare
a number:=1;
begin
while a<5 loop
dbms_output.put_line('a value'||a);
a := a+1;
end loop;
* end;
SQL> /
a value1
a value2
a value3
a value4
14
Example:
Q10) Write a PL/SQL block to print number from 1 to 5 using for loop statements
SQL> begin
for a in reverse 1..5 loop
dbms_output.put_line('a value'||a);
end loop;
end;
/
a value5
a value4
a value3
a value2
a value1
15
PROCEDURES:
Modular code :
A PL/SQL module is any complete logical unit of work. There are four types of
PL/SQL modules: 1) anonymous blocks that are run with a text script( you have used until
now), 2) Procedures, 3) Functions, and 4) Packages.
There are two main benefits to using modular code: 1) it is more reusable and 2) it is more
manageable.
Procedure:
A procedure is a module performing one or more actions: it does not need to return any
value.
The syntax for creating a procedure is
Example
16
Q16) create a procedure to add two number and call the block with a PL/SQL block?
Procedure created.
SQL> declare
a number := &a;
b number := &b;
begin
sum(a,b);
end;
/
Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Enter value for b: 20
old 3: b number := &b;
new 3: b number := 20;
c value 30
Q17) Create a procedure to add two number and return the value to a PL/SQL block?
17
Procedure created.
SQL> declare
a number := &a;
b number := &b;
d number;
begin
sum1(a,b,d);
dbms_output.put_line('d value '||d);
end;
/
Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Enter value for b: 30
old 3: b number := &b;
new 3: b number := 30;
d value 40
Q18) Create a procedure to accept sailors sid and return age of sailor to a PL/SQL block?
SQL> create or replace procedure sail(a in number,b out number)
is
c number;
begin
select age into c from sailors where sid = a;
b := c;
exception
when no_data_found then
dbms_output.put_line('no such sailors');
end;
/
Procedure created.
SQL> declare
a number := &a;
b number;
begin
sail(a,b);
dbms_output.put_line('sailors with '||a||'has age '||b);
18
end;
/
Enter value for a: 64
old 2: a number := &a;
new 2: a number := 64;
sailors with 64has age 35
FUNCTION:
The function does not necessarily have any parameters, but it must have a RETURN value
declared in the header, and it must return values for all the varying possible execution
streams.
Q19) Create a function to add two number and return the value to a PL/SQL block?
19
end;
/
Function created.
SQL> declare
a number:=10;
c number;
begin
c := f(a);
dbms_output.put_line('c value'||c);
end;
/
c value20
Q20) Create a function to accept sailors sid and return age of sailor to a PL/SQL block?
Function created.
SQL> declare
a number:= &a;
c number;
begin
c := sailf(a);
20
dbms_output.put_line('sailor with sid '||a||'has age '||c);
end;
/
Enter value for a: 58
old 2: a number:= &a;
new 2: a number:= 58;
sailor with sid 58has age 35
TRIGGER
21
END trigger_name ;
Eg.
CREATE OR REPLACE trigger before_product_update
BEFORE update of price on product for each row
when (new.price<old.price * 0.75)
begin
dbms_output.put_line(‘Product_id’||:old.prod_id);
dbms_output.put_line(‘Old_Price’||:old.price);
dbms_output.put_line(‘New_Price’||:new.price);
dbms_output.put_line(‘The price reduction is more than 25%’);
Insert into product_audit(prod_id,old_price,new_price)
values(:old.prod_id,:old.price,:new.price)
End before_produt_update;
FIRING A TRIGGER
To fire a trigger we must perform the DML operations on the table.
Eg : Update product set price = price * 0.70 where prod_id in (10,15);
Example:
To write a TRIGGER to ensure that SAILORS TABLE does not contain duplicate of
null values in SID column.
22
else
select count(*) into a from sailors where sid=:new.sid;
if(a=1) then
raise_application_error(-20002,'error:: cannot have duplicate sid');
end if;
end if;
END;
Trigger created.
23
Enter value for age:25.5
old 1: insert into sailors values((&sid,'&sname',&rating,&age)
new 1: insert into sailors values(22,’mana’,9,25.5)
insert into sailors values(22,’mana’,9,25.5))
*
ERROR at line 1:
ORA-20002: error:: cannot have duplicate sid
ORA-06512: at "SCOTT.TRIG1", line 9
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
SQL> /
Enter value for deptnp: 30
Enter value for dname: mana
Enter value for rating: 9
Enter value for age:25.5
old 1: insert into sailors values((&sid,'&sname',&rating,&age)
new 1: insert into sailors values(30,’mana’,9,25.5)
I row created
Types of Triggers:
24
DDL Triggers:
Users can create triggers on DDL statements like Alter, Create, Drop, etc., and
stored procedures based on a system that perform DDL operations.
We can also make After Trigger on DDL statements and cannot use Instead of the
clause.
DDL triggers are helpful to manage administrator tasks like; regulating auditing
database operations used to control actions on the SQL Server.
DML Triggers
In SQL Server we can create triggers on DML statements (like; INSERT, UPDATE,
and DELETE) and stored procedures that perform DML-like operations. DML
Triggers are of two types:
1. After Trigger: When execution of the action performed on SQL Server is about
to finish, then this trigger is fired. For example: When a user insert record in a
table, then the trigger related to this insert event will fire only after the ‘all
constraints pass in the row’, like; primary key, rules, etc. If it fails then SQL Server
won’t fire this trigger.
2. Instead of Trigger:
This trigger starts before the execution of the action performed by SQL Server. It
used before the action is performed opposite to the after trigger. The user can
apply Instead of clause like; update, deleted, insert triggers for a table. Actually, it
doesn’t include insert and all to the table.
For example:When a user insert record in a table, then the trigger related to this
insert event will fire only before the ‘all constraints passed’ in the row like
primary key, rules, etc. If it fails then SQL server will fire this trigger.
3. CLR Triggers
These are the special types of triggers that are based on Common Languages
Runtime in .net framework. CLR is integrated with the SQL Server 2008 and allows
triggers to be programmed in .net languages like; VB, C# etc.
User can write code for both DDL and DML triggers using CLR languages. For more
on CLR triggers
25
Logon Triggers
These triggers are used when a LOGON event of the SQL Server occurs. This event
gets raised when a user session is being established with the SQL Server after the
authentication phase has finished. All the messages defined in the trigger like;
error messages will be redirected to the error log of the SQL Server. If
authentication fails, then the logon triggers aren’t being fired. To audit server
controls and server sessions like login activity, limit the no. of sessions etc., these
triggers has used.
26