Unit4 - PL - SQL Oracle 2022
Unit4 - PL - SQL Oracle 2022
What is PL/SQL
• Procedural Language – SQL
• An extension to SQL with design features of
programming languages (procedural and object
oriented)
• PL/SQL and Java are both supported as internal
host languages within Oracle products.
Why PL/SQL
• Acts as host language for stored procedures and
triggers.
• Provides the ability to add middle tier business
logic to client/server applications.
• Improves performance of multi-query
transactions.
• Provides error handling
PL/SQL BLOCK STRUCTURE
DECLARE (optional)
- variable declarations
BEGIN (required)
- SQL statements
- PL/SQL statements or sub-blocks
……
EXCEPTION (optional)
- actions to perform when errors occur
…….
END; (required)
PL/SQL Block Types
Anonymous Procedure Function
p.sql f.sql
a.sql
PL/SQL Variable Types
• Scalar (char, varchar2, number, date, etc)
• Composite (%rowtype)
DECLARE
Syntax
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
Notice that PL/SQL
Examples includes all SQL types,
and more…
Declare
birthday DATE;
age NUMBER(2) NOT NULL := 27;
name VARCHAR2(13) := 'Levi';
magic CONSTANT NUMBER := 77;
valid BOOLEAN NOT NULL := TRUE;
PL/SQL- Assignment
• All variables must be declared before their use.
• The assignment statement
:=
is not the same as the equality =(comparison)
operator
=
• All statements end with a ; semicolon
DBMS_OUTPUT.PUT_LINE()
• Printing on the screen
• DBMS_OUTPUT is the package , defined with function
PUT_LINE( string variable ) .
• string variable value passed can be displayed on the
screen.
• Before using DBMS_OUTPUT.PUT_LINE( ..) , use SET
SERVEROUTPUT ON at SQL prompt
Example:
SET SERVEROUTPUT ON
DBMS_OUTPUT.PUT_LINE(‘ HELLO ….’);
DBMS_OUTPUT.PUT_LINE(‘MY Register Number ‘ ||to_char(12345));
|| symbol concatenates two strings.
PL/SQL FIRST PROGRAM
SET SERVEROUTPUT ON
DECLARE
message varchar2(20):= 'Hello, World! ';
BEGIN
dbms_output.put_line(message);
END;
/
PL/SQL Sample Program
/* Find the area of the circle*/
SET SERVEROUTPUT ON
DECLARE
pi constant number:=3.14;
radius number:=2;
area number;
BEGIN
area:=pi*radius*radius;
dbms_output.put_line('Area of circle is:'||area);
END;
/
PL/SQL sample program
--Find the area of the circle
SET SERVEROUTPUT ON
DECLARE
pi constant number:=3.14;
radius number:=&radius;
area number;
BEGIN
area:=pi*power(radius,2);
dbms_output.put_line('Area of circle is:'||area);
END;
/
Retrieving Column values into variables
SELECTING Columns Value Into Variables
Comments:
Single line comments -- This is 1st PL/SQL block
Multiline comments /* This is 1st PL/SQL block … */
%type and SELECT.. INTO..
DECLARE
v_radius circle.radius%TYPE;
V_area circle.area%TYPE;
BEGIN
SELECT radius INTO v_radius FROM circle WHERE
ROWNUM = 1;
DBMS_OUTPUT.PUT_LINE(' Radius = ' || v_radius);
V_area:=3.142*power(v_radius,2);
Update circle set Area=v_area where
radius=v_radius;
END;
%TYPE
%TYPE is used to declare a field with the same type as that of a
specified table's column:
DECLARE
v_EmpName emp.ename%TYPE;
v_empno emp.empno%TyPE;
v_sal emp.sal%type;
BEGIN
v_empno:=& v_empno;
SELECT ename,sal INTO v_EmpName,v_sal FROM emp WHERE
empno =v_empno;
DBMS_OUTPUT.PUT_LINE('Name = ' || v_EmpName|| ' Salary '
|| v_sal);
END;
/
%ROWTYPE
-- %ROWTYPE is used to declare a record with the same
types as found in the specified database table, view or
cursor:
DECLARE
v_emp emp%ROWTYPE;
BEGIN
v_emp.empno := 10;
v_emp.ename := 'XXXXXXX';
END;
/
%ROWTYPE
Set serveroutput on
DECLARE
v_dept dept%rowtype;
BEGIN
select * into v_dept
from dept where deptno=10;
DBMS_OUTPUT.PUT_LINE (v_dept.deptno);
DBMS_OUTPUT.PUT_LINE (v_dept.dname);
DBMS_OUTPUT.PUT_LINE (v_dept.loc);
END;
/
Example:
Assume that we have a table
STUD(RegNo, Name, Mark1,Mark2,Mark3)
• CHR(asciivalue)
• ASCII(string)
• LOWER(string)
• SUBSTR(string,start,substrlength)
• LTRIM(string)
• RTRIM(string)
• LPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|)
• RPAD(string_to_be_padded, spaces_to_pad, |string_to_pad_with|)
• REPLACE(string, searchstring, replacestring)
• UPPER(string)
• INITCAP(string)
• LENGTH(string)
COMMON IN-BUILT NUMERIC FUNCTIONS
• ABS(value)
• ROUND(value, precision)
• MOD(value,divisor)
• SQRT(value)
• TRUNC(value,|precision|)
• LEAST(exp1, exp2…)
• GREATEST(exp1, exp2…)
Conditional logic
Condition: Nested conditions:
If <cond> If <cond>
Then <command> Then
Elsif <cond2> If <cond2>
Then <command2> Then
Else <command1>
<command3> End if;
End if; Else <command2>
end if;
IF-THEN-ELSIF Statements
...
IF rating > 7 THEN
v_message := 'You are great';
ELSIF rating >= 5 THEN
v_message := 'Not bad';
ELSE
v_message := 'Pretty bad';
END IF;
...
CASE.. WHEN Statement
• The CASE statement selects one sequence
of statements to execute among multiple
sequences.
CASE e
WHEN e1 THEN r1
WHEN e2 THEN r2
…………………
WHEN en THEN rn
[ ELSE r_else ]
END CASE;
DECLARE CASE.. WHEN- Example
grade CHAR(1); BEGIN
grade := & grade;
CASE grade
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
DBMS_OUTPUT.PUT_LINE('A - Grade');
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');
DBMS_OUTPUT.PUT_LINE('B - Grade');
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');
DBMS_OUTPUT.PUT_LINE('C - Grade');
WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');
DBMS_OUTPUT.PUT_LINE('D - Grade');
WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');
DBMS_OUTPUT.PUT_LINE('F - Grade');
ELSE DBMS_OUTPUT.PUT_LINE('No such grade');
END CASE;
END;
Loops: Simple Loop
create table number_table(
num NUMBER(10) );
DECLARE
i number_table.num%TYPE := 1;
BEGIN
LOOP
INSERT INTO number_table VALUES(i);
i := i + 1;
EXIT WHEN i > 10;
END LOOP;
END;
Loops: FOR Loop
v_ename emp.ename%TYPE;
v_salary emp.sal%TYPE;
v_Budget dept.budget%Type;
updated_sal emp.sal%TYPE;
BEGIN
open c_emp; -- Open Cursor
loop
fetch c_emp into v_ename,v_salary,v_Budget;
exit when c_emp%notfound;
..Example-2
IF v_Budget<=200000 THEN
updated_sal:= v_salary+v_salary*0.05;
ELSIF v_Budget>200000 AND v_Budget<= 400000 THEN
updated_sal:= v_salary+v_salary*0.1;
ELSE
updated_sal:= v_salary+v_salary*0.15;
END IF;
DBMS_OUTPUT.PUT_LINE(' Name : '||v_ename);
DBMS_OUTPUT.PUT_LINE(' Old Salary : '||v_salary);
DBMS_OUTPUT.PUT_LINE(' New Salary : '||updated_sal);
DBMS_OUTPUT.PUT_LINE('====================');
end loop;
close c_emp; -- Close cursor
END;
/
Explicit Cursor- cursor for loop
Cursor for loop simplifies the usage of explicit cursor.
In each cursor PL/SQL following procedure is needed-
• Opening Cursor
• Fetching record and variable to hold fetched
values.
• Exiting from loop
• Closing loop