PL/SQL
• PL/SQL (Procedural Language/SQL) is a procedural extension
of Oracle.
• PL/SQL allows users and designers to develop complex
database applications
Structure of PL/SQL-Blocks
[<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.
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:
•
• <variable name> [constant] <data type> [not null] [:=
<expression>];
PL/SQL Character Data Types and Subtypes
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
PL/SQL Operator Precedence
• Operator precedence determines the grouping of terms in an
expression.
• This affects how an expression is evaluated.
• Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence
than the addition operator.
• 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.
• The precedence of operators goes as follows: =, <, >, <=, >=,
<>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN, IN.
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
+, -, || addition, subtraction, concatenation
== comparison
NOT logical negation
AND conjunction
OR inclusion
• Set serveroutput on;
CONDITIONAL CONTROL STATEMNETS
• 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.
•
Write a PL/SQL block to swap two numbers when the first number is greater
than second number ?
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;
/
• 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
•
• PL/SQL procedure successfully completed.
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;
Write a PL/SQL block to test whether the given
number is odd or even
• 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;
• /
•
• Enter value for a: 44
• old 2: a number(10) := &a;
• new 2: a number(10) := 44;
• 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;
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
• declare
• 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');
• end if;
• end;
•
• /
o/p
• Enter value for a: 22
• old 2: a number(10) := &a;
• new 2: a number(10) := 22;
• sailor 22 has grade B
•
• PL/SQL procedure successfully completed.
CASE:
• A case statement has the following structure:
•
• 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.
Write a PL/SQL block to print the day name for a given date?
• 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');
• 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
•
• PL/SQL procedure successfully completed.
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;
• END IF;
• …….
• STATEMENT N;
• END LOOP;
•
•
Write a PL/SQL block to print number from 1 to 5 using loop
statements
• 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;
• /
•
o/p
• 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.
WHILE LOOPS:
• A while loop has the following structure
•
• WHILE CONDITION LOOP
• STATEMNET 1;
• STATEMNET 2;
• ……
• STATEMNET N;
• End loop;
• 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.
Write a PL/SQL block to print number from 1 to
5 using while loop statements
• declare
• a number:=1;
• begin
• while a<6 loop
• dbms_output.put_line('a value'||a);
• a := a+1;
• end loop;
• end;
NUMERIC FOR LOOP:
• A numeric FOR loop is called numeric because it
requires an integer as its terminating value. Its structure is as
follows.
•
• FOR loop_counter IN[REVERSE]
Lower_limit..upper_limit LOOP
• STATEMENT 1;
• STATEMENT 2;
• ……
• STATEMENT N;
• END LOOP;
• The reversed word FOR marks the beginning of a FOR loop
construct.
• The variable loop_counter is an implicitly defined index
variable.
• There is no need to define the loop counter in the declaration
section.
• The values of the lower_limit and upper_limit are evaluated
once for the iteration of the loop.
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
•
• PL/SQL procedure successfully completed.
• SQL> begin
• for a in 1..5 loop
• dbms_output.put_line('a value'||a);
• end loop;
• end;
• /
•
• a value1
• a value2
• a value3
• a value4
• a value5
•
• PL/SQL procedure successfully completed.
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 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
• CREATE OR REPLACE PROCEDURE name
• [(PARAMETER 1 {IN,OUT,INOUT} DATATYPE(SIZE),
• PARAMETER 2 {IN,OUT,INOUT} DATATYPE(SIZE),
….
• PARAMETER N {IN,OUT,INOUT} DATATYPE(SIZE))]
• AS
• [local declaration]
• BEGIN
• Executable statements
• [EXCEPTION
• exception handler]
• END [name];
• create or replace procedure sum(a in number,b in number)
• is
• c number := 1;
• begin
• c := a+b;
• dbms_output.put_line('c value '||c);
• end;
• /
• SQL> declare
• a number := &a;
• b number := &b;
• begin
• sum(a,b);
• end;
• /
• FUNCTION:
• The syntax for creating a function is as follows:
•
• CREATE OR REPLACE FUNCTION name
• [(PARAMETER 1 {IN,OUT,INOUT} DATATYPE(SIZE),
• PARAMETER 2 {IN,OUT,INOUT} DATATYPE(SIZE),….
• PARAMETER N {IN,OUT,INOUT} DATATYPE(SIZE))]
• RETURN datatype
• IS
• [local declaration]
• BEGIN
• Executable statements
•
• END [name];
• 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.
• Create a function to add two number and return the value to a PL/SQL
block?
•
• SQL> create or replace function f(a in number)
• return number
• as
• b number;
• begin
• b:=10;
• b:=a+b;
• return b;
• end;
• /
• declare
• a number:=10;
• c number;
• begin
• c := f(a);
• dbms_output.put_line('c value'||c);
• end;
• /
• c value20
•
• PL/SQL procedure successfully completed.
•
• Create a function to accept sailors sid and return age of sailor to a PL/SQL block?
•
• SQL> create or replace function sailf(a in number)
• return number
• as
• b number;
• begin
• select age into b from sailors where sid=a;
• return b;
• exception
• when no_data_found then
• dbms_output.put_line('no such sailors');
• end;
• /
• declare
• a number:= &a;
• c number;
• begin
• c := sailf(a);
• 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
•
• PL/SQL procedure successfully completed.
•
•
Packages
Introducing to PL/SQL Package
• PL/SQL package is a group of related functions, procedures, types, cursors, etc.
PL/SQL package is like a library once written stored in the Oracle database and can
be used by many applications.
A PL/SQL package has two parts: package specification and package body.
• A package specification is the public interface of your applications. The public
means the stored function, procedures, types, etc., are accessible from other
applications.
• A package body contains the code that implements the package specification.
Exception Handling in PL/SQL
• An error occurred during the execution of program is called exception
in PL/SQL.
• PL/SQL provides the facility to catch errors by declaring conditions in
exception block in the program and necessary action to be taken to
rectify the error.
• Exception can be user defined (these are logical error defined by user)
or internally defined.
For example: The division by zero error.
Internal exceptions are raised automatically by the runtime system.
• User defined exception should be raised explicitly by RAISE
statements.
• Syntax
• DECLARE
• <declaration section>
• BEGIN
• <executable commands>
• EXCEPTION
• <define exception handling here >
• WHEN exception1 THEN
• exception1-handling-statements
• WHEN exception2 THEN
• exception2-handling-statements
• ........
• WHEN others THEN
• exception3-handling-statements
• END;
• Exception name Remark
• CURSOR ALREADY OPEN You have tried to open a cursor which is already open
• INVALID CURSOR Invalid cursor operation such as fetching from a closed cursor
• NO DATA FOUND A select . . . into or fetch statement returned no tuple.
• TOO MANY ROWS A select . . . into statement returned more than one tuple.
• ZERO DIVIDE You have tried to divide a number by 0
• Write a PL/SQL program to give message that no such a employee is present in a table.
• DECLARE
• c_id employee.dno%type := 9;
• c_name employee.lname%type;
• c_salary employee.salary%type;
• BEGIN
• SELECT lname, salary INTO c_name, c_salary
• FROM Employee
• WHERE dno = c_id;
• dbms_output.put_line ('Name:'|| c_name);
• dbms_output.put_line ('Designation:'||c_salary);
• EXCEPTION
• WHEN no_data_found THEN
• dbms_output.put_line('No such Employee exist!');
• WHEN others THEN
• dbms_output.put_line('Error!');
• END;
• /
•