You are on page 1of 53

PL/SQL

UNIT 4
What is PL/SQL?

 PL/SQL stands for Procedural Language extension


of SQL.
 
 PL/SQL is a combination of SQL along with the
procedural features of programming languages.

 It was developed by Oracle Corporation in the


early 90’s to enhance the capabilities of SQL. 
The PL/SQL Engine

 Oracle uses a PL/SQL engine to processes the


PL/SQL statements.

 A PL/SQL code can be stored in the client


system (client-side) or in the database
(server-side).
The PL/SQL Engine
 As shown in the above figure PL/SQL engine
executes procedural statements.

 It sends SQL part of statements to SQL


statement processor in the Oracle server.

 PL/SQL combines the data manipulating


power of SQL with the data processing
power of procedural languages.
SQL Statements Which Are
Allowed and Not Allowed in PL/SQL
 The only SQL statements allowed in a PL/SQL
program are
 SELECT,
 INSERT,
 UPDATE,
 DELETE and
 several other data manipulation statements.
 Data definition statements like
 CREATE,
 DROP, or
 ALTER are not allowed.
A Simple PL/SQL Program
A Simple PL/SQL Program
 SET SERVEROUTPUT ON is a command used
to access results from Oracle Server.

 A PL/SQL program is terminated by a “ / “.

 DBMS_OUTPUT is a package and PUT_LINE is a


procedure in it. 
Using Notepad Editor To Write The Program
Execution Of PL/SQL Program Written In
Notepad
 SQL > @EX1.sql

Welcome To PL/SQL Programming

PL/SQL procedure successfully completed.


Coding Guidelines
 Single-line comments are prefixed with two dashes --.

 Multiple-line comments can be enclosed with the


symbols /* and */.

 Variables and function identifiers can contain up to 30


characters.

 SQL functions can be used in PL/SQL.


Block Structure of PL/SQL
 PL/SQL is a block-structured language.
 i.e. Programs of PL/SQL contain logical
blocks.
Block Structure of PL/SQL

 As shown in the Figure PL/SQL block has three


parts. 
 Declaration: Necessary variables are declared in this
section. (Optional) 
 Begin: This section contain executable statements of
SQL and PL/SQL 
 Exception: Any error occurred while executing the
statements in begin part can be handled in this part. 
 End;
DECLARE SECTION
(OPTIONAL)
 Variables are declared in DECLARE section of PL/SQL. 
 Variables must be declared first before the usage.

 SQL datatype, such as


 CHAR,
 DATE,
 NUMBER,
 VARCHAR2 or any

 PL/SQL datatype like


 BOOLEAN,
 BINARY_INTEGER,
 %TYPE,
 %ROWTYPE, etc
DECLARING VARIABLES
DECLARE
birthdate DATE;
Emp_name VARCHAR2(10);
emp_count NUMBER(3) := 0;
acct_id VARCHAR2 (5) NOT NULL := 'AP001';
salary NUMBER(10, 2) :=10000;
bonus NUMBER(6, 2);
valid_id BOOLEAN

BEGIN
emp_name:=‘abc’;
birthdate:=‘19-Dec-1983’;
valid_id:= FALSE;
bonus := salary * 0.10;
CONSTANT
 In constant declarations, the reserved word
CONSTANT must precede the type specifier.

 DECLARE
 credit_limit CONSTANT number := 5000.00;
%TYPE
 DECLARE
 name EMPLOYEE.ename %TYPE;

 Gives PL/SQL variable name whatever type was


declared for the ename column in table
EMPLOYEE.
%TYPE
 The %TYPE attribute provides the datatype of a
variable or database column.
 This is particularly useful when declaring
variables that will hold database values.
 It has two advantages.
 First, you need not know the exact data type of the column.
 Second, if you change the database definition of column
(for example make it a longer character string), the datatype
of variable changes accordingly at run time.
%ROWTYPE
 In PL/SQL, records are used to group data.
 A record consists of a number of related fields in which data values
can be stored.
 The %ROWTYPE attribute provides a record type that represents a
row in a table.
 The record can store an entire row of data selected from the table or
fetched from a cursor or cursor variable.
 Columns in a row and corresponding fields in a record have the
same names and data types.
 In the example below, you declare a record named dept_rec.
 Its fields have the same names and datatypes as the columns in
the dept table.

 Example for declaring RECORD Variable


 DECLARE dept_rec dept%ROWTYPE;
Begin Section
 This is the executable section which can contain
constructs such as assignments, branches, loops,
procedure calls, and triggers.

 PL/SQL is not case sensitive.


SQL Statements in PL/SQL
 The following code block shows how to run DML statements
in PL/SQL. Basically they look similar to the SQL.
 Note that the SELECT statement retrieves the single-row
value and store into a variable using INTO clause.
DECLARE
v_sal employee.sal%TYPE;
BEGIN
    INSERT INTO employee VALUES (6, 'TOM LEE', 10000);
    UPDATE employee SET sal = sal + 5000 WHERE empno = 6;
  SELECT sal INTO v_sal FROM employee WHERE empno = 6;
    DBMS_OUTPUT.PUT_LINE('Salary increased to ' || v_sal); 
  DELETE FROM employee WHERE empno = 6;
      COMMIT;
END;
/
Conditional Statements

1. IF THEN Statement

2. IF THEN ELSE Statement

3. IF THEN ELSIF Statement

4. Nested IF
IF THEN Statement
Syntax:

IF condition THEN
Statement1;
END IF;
Using the IF-THEN Statement
 The simplest form of IF statement associates a
condition with a sequence of statements enclosed by
the keywords THEN and END IF (not ENDIF)

 The sequence of statements is executed only if the


condition is TRUE.

 If the condition is FALSE or NULL, the IF statement


does nothing.

 In either case, control passes to the next statement.


Using a Simple IF-THEN
Statement
DECLARE
sales NUMBER(8,2) := 10100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 10;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
UPDATE employee SET sal = sal + bonus
WHERE empno = emp_id;
END IF;
END;
/
IF THEN ELSE Statement
 Syntax:

IF condition THEN
Statement1;
ELSE  
Statement 2;
END IF;
Using the IF-THEN-ELSE
Statement
 The second form of IF statement adds the
keyword ELSE followed by an alternative
sequence of statements.

 The statements in the ELSE clause are executed


only if the condition is FALSE or NULL.

 The IF-THEN-ELSE statement ensures that one or


the other sequence of statements is executed.
Using a Simple IF-THEN-ELSE
Statement
DECLARE
sales NUMBER(8,2) := 12100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
ELSE
bonus := 50;
END IF;
UPDATE employee SET sal = sal + bonus
WHERE emp_no = emp_id;
END;
/
IF THEN ELSIF Statement
 Syntax:
IF condition1 THEN
  Statement1;
  Statement2;
ELSIF condtion2 THEN
  Statement3;
ELSE  
Statement4;
END IF;
Using the IF-THEN-ELSIF
Statement
 If the first condition is FALSE or NULL,
the ELSIF clause tests another condition.
 An IF statement can have any number
of ELSIF clauses;
 the final ELSE clause is optional.
 Conditions are evaluated one by one from top to
bottom.
 If any condition is TRUE, its associated sequence of
statements is executed and control passes to the next
statement.
 If all conditions are false or NULL, the sequence in
the ELSE clause is executed.
Using the IF-THEN-ELSIF
Statement
DECLARE
sales NUMBER(8,2) := 20000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus := 500;
ELSE
bonus := 100;
END IF;
UPDATE employee SET sal = sal + bonus WHERE empno = emp_id;
END;
/
Another Example For IF-THEN-
ELSIF
DECLARE grade CHAR(1);
BEGIN
grade := 'B';
IF grade = 'A' THEN
DBMS_OUTPUT.PUT_LINE('Excellent');
ELSIF grade = 'B' THEN
DBMS_OUTPUT.PUT_LINE('Very Good');
ELSIF grade = 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); ELSIF grade = 'D' THEN
DBMS_OUTPUT. PUT_LINE('Fair');
ELSIF grade = 'F' THEN
DBMS_OUTPUT.PUT_LINE('Poor');
ELSE
DBMS_OUTPUT.PUT_LINE('No such grade');
END IF;
END;
/
Nested IF
 Syntax:
IF condition1 THEN
IF condition2 THEN
  Statement1;  
END IF;
ELSE 
Statement2;
END IF;
Using Nested IF
DECLARE
sales NUMBER(8,2) := 12100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
IF sales > quota THEN
bonus := 50;
ELSE
bonus := 20;
END IF;
ELSE
bonus=10;
END IF;
UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
END; /
Write a PL/SQL block to accept two numbers
and print the maximum numbers
DECLARE
A number(3);
B number(3);
BEGIN
A:=&a;
B:=&B;
If (A>B) THEN
DBMS_OUTPUT.PUT_LINE(‘Largest number is :’|| A);
ELSE
DBMS_OUTPUT.PUT_LINE(‘Largest number is :’|| B);
END IF;
END;
/
Using CASE Statements
 Like the IF statement, the CASE statement selects one
sequence of statements to execute.

 However, to select the sequence, the CASE statement uses a


selector rather than multiple Boolean expressions.

 A selector is an expression whose value is used to select one


of several alternatives.
Using the CASE-WHEN
Statement
DECLARE WHEN 'F'
THEN
grade CHAR(1);
DBMS_OUTPUT.PUT_LINE('Poor');
BEGIN ELSE
grade := 'B';
CASE grade DBMS_OUTPUT.PUT_LINE('No
such grade');
WHEN 'A' THEN END CASE;
DBMS_OUTPUT.PUT_LINE('Excellent'); END;
WHEN 'B' THEN /
DBMS_OUTPUT.PUT_LINE('Very
Good');
WHEN 'C' THEN
DBMS_OUTPUT.PUT_LINE('Good');
WHEN 'D' THEN
DBMS_OUTPUT.PUT_LINE('Fair');
Iterative Statements in PL/SQL
 An iterative control Statements are used when we
want to repeat the execution of one or more
statements for specified number of times.
 These are similar to those in the other
programming languages like C, C++ or Java.
 There are three types of loops in PL/SQL:
• Simple Loop
• While Loop
• For Loop
Simple Loop
 A Simple Loop is used when a set of statements is to be
executed at least once before the loop terminates.
 An EXIT condition must be specified in the loop,
otherwise the loop will get into an infinite number of
iterations.
 When the EXIT condition is satisfied the process exits
from the loop.
 The General Syntax to write a Simple Loop is:
LOOP
statements;
EXIT [WHEN condition];
END LOOP;
Write a PL/SQL block to display first 10 numbers starting from
a given number using simple loop.

DECLARE
start_no number(3);
counter number(2);
BEGIN
counter:=0;
start_no:=&start_no;
LOOP
counter:=counter+1;
DBMS.OUTPUT.PUT.LINE(‘Number : start_no);
Start_no = start_no+1;
EXIT WHEN counter >10;
END LOOP;
END;
/
Simple Loop
 These are the important steps to be followed while
using Simple Loop.
 Initialize a variable before the loop body.
 Increment the variable in the loop.
 Use a EXIT WHEN statement to exit from
the Loop.
 If you use a EXIT statement without WHEN
condition, the statements in the loop is
executed only once.
Using the EXIT Statement
 When an EXIT statement is encountered, the loop completes immediately and control
passes to the statement immediately after END LOOP
 Example

DECLARE
x NUMBER := 0;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || x);
x := x + 1;
IF x > 3 THEN
EXIT;
END IF;
END LOOP;
-- After EXIT, control resumes here
DBMS_OUTPUT.PUT_LINE (' After loop: x = ' || x);
END;
/
OUTPUT
Inside loop: x = 0
Inside loop: x = 1
Inside loop: x = 2
Inside loop: x = 3
After loop: x = 4
What is the O/P?
 Example

DECLARE
x NUMBER := 0;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || x);
x := x + 1;
EXIT;
END LOOP;
-- After EXIT, control resumes here
DBMS_OUTPUT.PUT_LINE (' After loop: x = ' || x);
END;
/
While LOOP
 A WHILE LOOP is used when a set of statements
has to be executed as long as a condition is true.
 The condition is evaluated at the beginning of each
iteration. The iteration continues until the condition
becomes false.
 The General Syntax to write a WHILE LOOP is:
WHILE <condition>
LOOP
Statements;
END LOOP;
For LOOP
 A FOR LOOP is used to execute a set of statements for a
predetermined number of times.
 Iteration occurs between the start and end integer values given.
 The counter is normally incremented by 1. The loop exits when
the counter reaches the value of the end integer.
 Syntax
FOR variable IN [REVERSE] start..end
LOOP
Statements;
END LOOP;
For LOOP
• Variable – is used as loop index. This variable
need not be declared and is always
incremented by 1.
• Start is an integer value. Represents the
beginning of loop index
• End is an integer value. Represents the last
value of loop index
• REVERSE starts the loop in reverse order,
starting from End to Start.
Write a PL/SQL block to print 10 numbers
starting from 1 using FOR loop.

BEGIN
FOR i IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
Write PL/SQL block to print 10 sequential numbers in
descending order starting from 10.

BEGIN
FOR i IN REVERSE 1..10
LOOP

DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
Write a PL/SQL block to check whether the given
string is a palindrome or not

DECLARE
IF str1=str2 THEN
str1 varchar2(20);
str2 varchar2(10); DBMS_OUTPUT.PUT_LINE(
chr1 char(1); str1|| ‘is palindrome’);
len number(2);
BEGIN ELSE
str1:=&str1;
DBMS_OUTPUT.PUT_LINE(
len:=LENGTH(str1);
str1|| ‘is not a palindrome’);
FOR i in reverse 1..len
LOOP
chr1:=SUBSTR(str1,i,1);
str2:=str2 || chr1;
END LOOP;
Sequential Control(Unstructured Batch)

 The GOTO statement changes the flow of control


in a PL/SQL block.
 The entry point into such a block of code is marked
using the tags <<user defined names>>.
 The GOTO statement can make use of this user
defined name to jump into that block of code for
execution.
 Syntax: GOTO <<user defined name>>;
Write a PL/SQL block to display the given number is
odd or even using GOTO statement

DECLARE <<even_no>>
num1 number(3);
rem number(3); DBMS_OUTPUT.PUT_LINE
(‘number is
BEGIN even’);
num1:=&num1; <<odd_no>>
rem:=mode(num1,2);
DBMS_OUTPUT.PUT_LINE
IF rem=0 THEN (‘number is
goto even_no; odd’);
ELSE END;
goto odd_no;
END IF;

You might also like