Lecture Notes Unit5 chapter 15 PL/SQL Programming

Murugan146644 831 views 32 slides Jul 21, 2024
Slide 1
Slide 1 of 32
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32

About This Presentation

Description:
Welcome to the comprehensive guide on Relational Database Management System (RDBMS) concepts, tailored for final year B.Sc. Computer Science students affiliated with Alagappa University. This document covers fundamental principles and advanced topics in RDBMS, offering a structured appr...


Slide Content

RDBMS -Unit V
Chapter 15
PL/SQL
Prepared By
Dr. S.Murugan, Associate Professor
Department of Computer Science,
AlagappaGovernment Arts College, Karaikudi.
(Affiliated by AlagappaUniversity)
Mailid: [email protected]
Reference Book:
LEARN ORACLE 8i, JOSE A RAMALHO

PL/SQL
➢PL/SQLisanextensionoftheSQLlanguage.
➢Itisaprocedurallanguage.
➢PL/SQL combines the SQL language’s ease of data
manipulation and the procedural language’s ease of
programming.
➢With the PL/SQL language, we can create schema
objects, including Stored procedures and functions,
Packages, Triggers, Cursors.

PL/SQL
➢Storedproceduresandfunctions.Astoredprocedure
isaPL/SQLprogramthatcanbeenabledbyan
application,atrigger,oranOracletool.
➢Thebasicdifferencebetweenaprocedureanda
functionisthataprocedureexecutesitscommands
andafunctionexecutescommandsandreturnsa
result.
➢Packages.Apackageisafilethatcontainsagroupof
functions,cursors,storedprocedures,andvariablesin
oneplace.

PL/SQL
➢Triggers.AtriggerisaPL/SQLprogramthatisstored
inthedatabaseandexecutedimmediatelybeforeor
aftertheINSERT,UPDATE,andDELETE
commands.
➢Cursors.OracleusesworkspacestoexecutetheSQL
commands.ThroughPL/SQLcursors,itispossibleto
nametheworkspaceandaccessitsinformation.

PL/SQL BLOCK
➢ThebasicstructureofPL/SQLblockisgivenbelow:

PL/SQL BLOCK
TherearethreepartstothePL/SQLblock:
➢Declarationsection/Declare(optional),inwhichall
theobjectsaredeclared.
➢Executionsection/Begin,inwhichthePL/SQL
commandsareplaced.
➢Exceptionsection/Exception(optional),inwhichthe
errorsarehandled.

PL/SQL BLOCK -Declaration Section
Inthedeclarationsection,thedevelopercanperformthe
following:
➢Declare the name of an identifier -PI.
➢Declare the type of identifier (constantor variable).
➢Declare the data type of the identifier. -REAL
➢Assign (initialize) contents to the identifier. –3.14
Ex:PI CONSTANT REAL := 3.14

PL/SQL BLOCK -Variables
➢Thevariablescancontainanydatatypethatisvalid
forSQLandOracle(suchaschar,number,long,
varchar2,anddate)inadditiontothesetypes:
➢BooleanCanbeassignedthevaluesTrue,False,or
NULL.
➢Binary_integerAcceptsnumbersbetween
-2,147,483,647and2,147,483,647.
➢PositiveAcceptsnumbersfrom1to2,147,483,647.
➢NaturalAcceptsnumbersfrom0to2,147,483,647.

PL/SQL BLOCK -Variables
➢%typeAssignstothevariablethatisbeingcreatedthe
samedatatypesusedbythecolumnthatisbeingused.
Toaccessthefieldofdeptnofromdept.tableand
assignedtodeptp.
deptp:=dept.deptno%type;
➢%rowtypeDeclaresacomposedvariablethatis
equivalenttotherowofthetable.
➢Afterthevariableiscreated,thefieldsofthetablecan
beaccessed,usingthenameofthisvariablefollowed
byaperiodandthenameofthefield:
Empline:=emp%rowtype
➢Afterthevariableiscreated,youcanusethefollowing

PL/SQL BLOCK -Variables
➢Afterthevariableiscreated,youcanusethefollowing
expressiontoassignacolumntoanothervariable:
Newvar:=empline.ename;

PL/SQL BLOCK -Variables
➢Therearetwowaystoassignvaluestoavariable.The
firstistousetheassignmentoperator“:=”:
tot:=price*margin;
increase:=sal*1.10;
➢Thesecondwaytoassignvaluestovariablesistouse
theSELECTcommandtoassignthecontentsofthe
fieldsofatabletoavariable:
SELECTsal*0.10INTOincreasedFROM
empWHEREempno=emp_id;

PL/SQL BLOCK -Constant
➢Thedeclarationofaconstantissimilartothe
declarationofavariable,excepttoaddthekeyword
Constantafterthenameoftheconstant:
PICONSTANTREAL:=3.14;
➢Eachvariableorconstantmustbespecifiedwithits
name,type,and,optionally,initialvalue.Alltherows
mustendwithasemicolon:
DECLARE
Cust_namevarchar2(20);
Creditnumber(5,2):=100;

PL/SQL BLOCK -Execution Section
➢ThissectionbeginswiththeBegindeclaration.
➢ThissectioncancontainSQLcommands,logical
controlcommands,andassignmentcommands,aswell
asothercommands.
➢Allcommandsarealwaysendwithasemicolon.

PL/SQL BLOCK -Exception
➢Inthissection,thedevelopercanusecommandsto
handleanerrorthatoccursduringtheexecutionofa
PL/SQLprogram.

How PL/SQL Works
➢PL/SQLisanenginethatmakesuppartoftheOracle
server.
➢Itexecutestheproceduralcommandsandpassesthe
SQLcommandsfortheOracleservertoprocess.
➢PL/SQLblockscanbecreatedwithanyofthe
processingeditors.(Ex:WindowsNotepad)
➢ToexecuteaPL/SQLprogramorscript,youcanuse
SQL*Plus,whichallowscreating,storing,and
executingPL/SQLblocks.

How PL/SQL Works

Example Program
➢Step1:Typetheprogramineditorandexecuteusing
@symbol.
➢SQL>setserveroutputon;

Example Program for variable and constant

Control Structures
➢PL/SQLhassomecommandstocontroltheexecution
flowoftheprogram.Theyareresponsiblefordecision
makinginsidetheapplication.
➢controlstructuresinPL/SQL,whichcanbedivided
intoconditioncontrolstructures(selection),sequence
structures,andrepetitionoriterationstructures.
➢Differenttypesofstructureexplainedinthefigure
15.3.

Control Structures

The IF..THEN Command
➢TheIF..THENcommandevaluatesaconditionand
executesoneormorerowsofcommandsonlyifthe
analyzedconditionistrue.
➢Ithastwovariationsasfollows:

The IF..THEN Command
➢Insyntax1,thecommandsthatappearbetweenthe
THENandENDIFclauseswillbeexecutedonlyif
theconditionistrue.
Example:
declare
salnumber(7,2);
begin
select salary into salfrom emp2 where eno=101;
IF SAL>= 5000 THEN
UPDATE EMP2 SET salary = salary*1.2;
END IF;
dbms_output.put_line(sal);
end;
/

The IF..THEN Command
In syntax2, more than one condition can be analyzed
and, therefore, several actions can be executed:
1. create table emp2(enonumber(3), salary number(7,2))
2. insert into emp2 values (102, 1500)
3. Type the following program and execute:
declare
salnumber(7,2);
begin
select salary into salfrom emp2 where eno=101;
IF sal<2000 THEN
UPDATE EMP2 SET salary = salary * 1.2;
ELSIF sal<3000 THEN
UPDATE EMP2 SET salary = salary * 1.3;
ELSE
UPDATE EMP2 SET salary = salary * 1.4;
END IF;
dbms_output.put_line(sal);
end;

The IF..THEN Command
➢Ifthemainconditionistrue,thefollowingcommands
willbeexecuteduntilanotherELSIForELSEclause
isfound.
➢IfthefirstELSIFconditionisfalse,theprogramtests
thesecondcondition,andsoon.
➢Whenthefirsttrueconditionisfound,itscommands
areexecuted,andtheprogramjumpstotherowafter
theENDIFcommand.

The LOOP Command
➢TheLOOPcommandinitializesagroupofcommands
indefinitely,oruntilaconditionforcesa“break”inthe
loopandtheexecutionoftheprogramtoanother
place.
➢TheEXITcommandisresponsibleforinterruptingthe
loopexecution:

The LOOP Command -Example
LOOPwith IF Loop with WHEN
declare
I number(3);
begin
I := 1;
Loop
I := I+1;
DBMS_OUTPUT.PUT_LINE(I);
IF I>= 30 THEN
EXIT;
END IF;
END LOOP;
END;
/
declare
I number(3);
begin
I := 1;
Loop
I := I+1;
DBMS_OUTPUT.PUT_LINE(I);
EXIT WHEN I>= 30;
END LOOP;
END;
/
➢Thefollowinglooprepeateduntilthecountervariable
Ibecome30.

The FOR..LOOP Command
➢TheFOR..LOOPcommandisavariationoftheLOOP
command.
➢Here,thecommandsareautomaticallyexecuteduntil
anevaluatedconditionreturnsfalse.
Syntax:
FOR <counter> IN [REVERSE] <initial_value> . . <final_value>
LOOP
<commands>
END LOOP;

The FOR LOOPCommand -Example
Example:
declare
j number(3);
begin
FOR j IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(j);
END LOOP;
END;
/
➢TheFORcommandinitializesacontrolvariablecalledJ,which
hastheinitialvalueof1.
➢ThecommandswillbeexecuteduntilENDLOOPisfound.
➢Then,thecontrolreturnstotheFORcommand,which
incrementsthevariableandanalyzesthemastercondition,i.e.,
whetherthevalueofJislessthanthefinalvalue.
➢Whenthishappensthecycleisreinitialized.

The FOR LOOPCommand -Example
➢TheREVERSEclausemakesthecounterstartwiththe
highestvalueanddecreaseuntilitreachesthelowest
value.
declare
j number(3);
begin
FOR j IN reverse 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(j);
END LOOP;
END;
/

The WHILE Command
➢TheWHILEcommandisanothercontrolstructure.
Thisstructureonlyexecutesthecommandsifthe
analyzedconditionistrue.
declare
x number(3);
begin
x:=1;
while x<=20 loop
DBMS_OUTPUT.PUT_LINE(x);
x:=x+1;
END LOOP;
END;
/

Integrating SQL in a PL/SQL Program
➢SQLcommandscanbeinsertedintheexecution
sectionofaPL/SQLblock.
➢Thedevelopercanuse(reference)avariableor
constantdeclaredinthedeclarationsection.
➢InsideaPL/SQLprogramtheSELECTcommanduses
anewclausecalledINTOthatallowstransferringthe
contentsofthefieldsinarowtothevariablesin
memory.
➢Command:SETSERVEROUTPUT ON,GET
(Retreivethefile),RUN(@Executetheprogram)

Integrating SQL in a PL/SQL Program
Declare
Var_namenumber(7,2);
Begin
SELECTsalaryINTOVar_nameFROMemp2whereeno
=101;
dbms_output.put_line('salary='||Var_name);
End;
/
➢Notethattoattributecontentstoafieldinavariable,
theSELECTcommandmustreturnonlyonerow;
➢otherwiseanerrorwilloccur,sinceseveralvaluesare
beingassignedtoonlyonevariable.