PLSQL Examples
PLSQL Examples
PLSQL
NOTES
ORACLE9i
GauravBhide
_____________________________________________________________________
FocusTrainingServices1
PLSQLNOTES
INDEX
VARIABLEDECLARATION........05
CONTROLSTATEMENTS.........18
COMPOSITEVARIABLES........26
EXPLICITCURSORS..........31
EXCEPTIONS.............43
PROCEDURES.............52
FUNCTIONS.............55
PACKAGES..............58
ORACLEPACKAGES..........67
DYNAMICSQL............75
TRIGGERS..............77
_____________________________________________________________________
FocusTrainingServices2
PLSQLNOTES
ServerConnection
_____________________________________________________________________
FocusTrainingServices3
PLSQLNOTES
ImportantInstructions
Eachstudenthashisownunixloginidtoserver.
Usesshlcommandtologintoserver.
e.g.sshlgaurav172.24.0.254
inabovecasegauravisunixid.
Defaultpasswordisxxxxxxforallstudents.
Change password using passwd commnad after first
login.
Afterlogininserver,setdatabasenameinORACLE_SID
variable.
e.g.exportORACLE_SID=rahul
inabovecaserahulisdatabasename.
Conncet to database using your oracle sql login name
andpassword.
e.g. sqlplusgaurav/gaurav
Inabovecaseusernameisgauravandpasswordisalso
gaurav.
Foreachstudentoracleloginidandpasswordwillbe
hisname.
Connect to oracle from where you are writing your
plsqlprograms.
e.g.[gaurav@server1~]$cdplsql/
[gaurav@server1~]$sqlplusgaurav/gaurav
_____________________________________________________________________
FocusTrainingServices4
PLSQLNOTES
VARIABLEDECLARATION
_____________________________________________________________________
FocusTrainingServices5
PLSQLNOTES
Thisisthefirstprograminplsqltoprinthelloworld.
createorreplaceproceduresp11
as
FirstProgramofPlsql
ThisProgramPrints
HelloWorldontheScreen
begin
dbms_output.put_line('HelloWorld');
end;
ToCompileStoredProcedures
Type@filename/procedurename.sqlonSQLPrompt
Toseetheoutputonsqlprompttypecommand
'setserveroutputon'whenyouareloggedin.
TOExecuteStoredProcedures
Typeexecprocedure_name
OUTPUT
SQL>@sp11.sql
Procedurecreated.
Noerrors.
SQL>execsp11
HelloWord
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices6
PLSQLNOTES
Thisprogramshowshowtocheckerrorsinprocedures.
createorreplaceproceduresp11_1
as
ThisProgramshowshowtoReadErrors
begin
dbms_output.put_line('HelloWorld')
Semicolonmissingattheend
end;
/
ToSeeErrorsType'showerrors'onSQLprompt
Youcanwrite'showerrors'attheendofprocedure.
OUTPUT
SQL>@sp11_1.sql
Warning:Procedurecreatedwithcompilationerrors.
SQL>showerrors
ErrorsforPROCEDURESP11_1:
LINE/COLERROR
7/1PLS00103:Encounteredthesymbol
"END"whenexpecting
oneofthefollowing:
:=.(%;
Thesymbol";"wassubstituted
for"END"tocontinue.
_____________________________________________________________________
FocusTrainingServices7
PLSQLNOTES
Variabledeclarationandassigningvaluetovariables.
createorreplaceproceduresp12
ThisProgramShowsThat
HowDeclaringVariables
as
l_my_namevarchar2(20):='gaurav';
CharacterVariable
l_my_agenumber:=23;
NumberVariable
begin
dbms_output.put_line('MyNameis'||l_my_name);
dbms_output.put_line('MyAgeis'||l_my_age);
end;
/
showerrors
OUTPUT:
SQL>@sp12.sql
Procedurecreated.
Noerrors.
SQL>execsp12
MyNameisgaurav
MyAgeis23
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices8
PLSQLNOTES
Passingvaluetovariables.
createorreplaceproceduresp13(l_name
varchar2,l_agenumber)
ThisProgramshowshowto
PassValuestoprocedures
Acceptvaluesinvariable
withoutspecifingitslength
as
begin
dbms_output.put_line('NameEnteredByUser:'||l_name);
dbms_output.put_line('AgeEnteredByUser:'||l_age);
end;
/
showerrors
OUTPUT:
SQL>@sp13.sql
Procedurecreated.
Noerrors.
SQL>execsp13('gaurav',22);
NameEnteredByUser:gaurav
AgeEnteredByUser:22
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices9
PLSQLNOTES
Selectingvaluesfromdatabasetables.
createorreplaceproceduresp13_1
ThisProgramsShowshowto
ExecuteSQLquriesfromplsql
as
l_employee_idnumber:=100;
l_employee_namevarchar2(30);
begin
selectlast_name
intol_employee_name
fromemployees
whereemployee_id=l_employee_id;
intoclausecopiesselectedcolumn'svalue
intogivenvariables
dbms_output.put_line('EmployeesNameis:'||
l_employee_name);
end;
/
showerrors
OUTPUT
SQL>@sp13_1.sql
Procedurecreated.
Noerrors.
SQL>execsp13_1
EmployeesNameis:King
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices10
PLSQLNOTES
Useof%typevariable.
createorreplaceproceduresp15(l_employee_idnumber)
ThisProgramshows
howtousevariableswithsamedatatypefromtables
Objective
AcceptEmployeeIDFromUser
PrintNameofThatEmployee
as
l_last_nameemployees.last_name%type;
begin
selectlast_name
intol_last_name
fromemployees
whereemployee_id=l_employee_id;
dbms_output.put_line('NameofEmployeeis:'||l_last_name);
end;
/
showerrors
SQL>@sp15
Procedurecreated.
Noerrors.
SQL>setserveroutputon
SQL>execsp15(200);
NameofEmployeeis:Whalen
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices11
PLSQLNOTES
Useof%rowtypevariable
createorreplaceproceduresp14
ThisProgramshows
howtodeclareVariablesWith%TypeAttribute
MeansSameDataTypeasinTable
as
l_last_nameemployees.last_name%type;
Inthiscasedatatypeof
l_last_nameissameas
datatypeofcolumnlast_namefromemployees
begin
selectlast_name
intol_last_name
fromemployees
whereemployee_id=101;
dbms_output.put_line(l_last_name);
end;
/
showerrors
OUTPUT:
SQL>@sp14.sql
Procedurecreated.
Noerrors.
SQL>execsp14
Kochhar
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices12
PLSQLNOTES
Scopeofvariablesinprocedure.
createorreplaceproceduresp16
ThisProgramshows
ScopeOfVariableinStoredProcedure
as
l_nonumber:=600;
l_msgvarchar2(20):='GlobalVariable';
begin
<<Inner_Block1>>
declare
l_nonumber:=1;
l_msgvarchar2(20):='Localvariable';
begin
l_no:=l_no+1;
dbms_output.put_line('InInnerBlock1');
dbms_output.put_line(l_no);
dbms_output.put_line(l_msg);
end;
<<Inner_Block2>>
declare
l_nonumber:=100;
begin
dbms_output.put_line('InInnerBlock2');
dbms_output.put_line(l_no);
dbms_output.put_line(l_msg);
end;
dbms_output.put_line('InMain');
dbms_output.put_line(l_no);
dbms_output.put_line(l_msg);
end;
/
showerrors
Variablesdeclaredinmainprocedure(Outermostvariable)are
globalvariables.
Globalvariablescanbeaccessableinallinnerprocedures.
Innerprocedurescandefinetheirownvariableswithsamename
asglobalvariableandaccess.
Butitisnotgoodprogramingpractice.
_____________________________________________________________________
FocusTrainingServices13
PLSQLNOTES
OUTPUT
SQL>@sp16.sql
Procedurecreated.
Noerrors.
SQL>execsp16
InInnerBlock2
2
LocalVariable
InInnerBlock2
100
GlobalVariable
InInnerMain
600
GlobalVariable
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices14
PLSQLNOTES
DMLStatementsinProcedure
createorreplaceproceduresp17
ThisProgramsshows
ExecutingDMLstatementinPlsql
as
begin
InsertingDataFromPlsqlProcedure
insertintotest(test_id,test_name)
values(1,'sql');
insertintotest(test_id,test_name)
values(2,'plsql');
UpdatingDataFromPlsqlProcedure
updatetest
settest_id=20
wheretest_id=2;
DeletingDataFromPlsqlProcedure
deletefromtest
wheretest_id=20;
commit;
end;
/
showerrors
OUTPUT
createtabletest(test_idnumber,test_namevarchar2(10));
Tablecreated.
SQL>@sp17.sql
Procedurecreated.
Noerrors.
SQL>execsp17
PL/SQLproceduresuccessfullycompleted.
SQL>select*fromtest;
TEST_IDTEST_NAME
1sql
_____________________________________________________________________
FocusTrainingServices15
PLSQLNOTES
ImplicitCursorsinPlsql
createorreplaceproceduresp18
ThisProgramshowshowtouse
SqlCursorAttributes(Setbydefaultbysql)
SQL%ROWCOUNT
SQL%FOUND
SQL%NOTFOUND
SQL%ISOPEN
as
begin
insertintotest(test_id,test_name)values(3,'RedHat');
ifsql%foundthen
dbms_output.put_line('Rowisinserted');
endif;
delete
fromtest;
dbms_output.put_line(sql%rowcount||'
Rowsareselected');
delete
fromtest;
ifsql%notfoundthen
dbms_output.put_line('Norowisdeleted');
endif;
end;
/
showerrors
Implicitcursorsareimplicitlydefinebyoracle.
Theyreturninformationaboutresultofquery.
SQL%ROWCOUNTreturnsnumberofrowsaffectedbyquery.
SQL%FOUNDreturntrueifatleastonerowisaffectedbyquery.
SQL%NOTFOUNDreturntrueifzerorowsareaffectedbyquery.
_____________________________________________________________________
FocusTrainingServices16
PLSQLNOTES
SQL>@sp18.sql
Procedurecreated.
Noerrors.
SQL>select*fromtest;
TEST_IDTEST_NAME
1sql
SQL>execsp18
Rowisinserted
2Rowsareselected
Norowisdeleted
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices17
PLSQLNOTES
CONTROLSTATEMENTS
_____________________________________________________________________
FocusTrainingServices18
PLSQLNOTES
ControlStatement:IfElseCondition
createorreplaceproceduresp21(p_employee_idinnumber)
as
Thisprocedurewillgiveasalaryraise
toanemployee.Rulesfortheraiseareasfollows
1.20%forEmployeesworkingwithusforatleast12years
andwhosesalaryislessthanRs.6000/
2.15%forEmployeeswhosesalarylessthanRs.6000/
3.10%foremployeesworkingwithusforatleast12years
l_hire_dateemployees.hire_date%type;
l_salaryemployees.salary%type;
l_years_of_servicenumber:=0;
l_new_salarynumber:=0;
begin
selecthire_date,
salary
intol_hire_date,
l_salary
fromemployees
whereemployee_id=p_employee_id;
l_years_of_service:=months_between(sysdate,l_hire_date)/12;
ifl_salary<6000andl_years_of_service>12then
l_new_salary:=l_salary*1.2;
dbms_output.put_line('Giving20%raise');
elsifl_salary<6000then
l_new_salary:=l_salary*1.15;
dbms_output.put_line('Giving15%raise');
elsifl_years_of_service>12then
l_new_salary:=l_salary*1.1;
dbms_output.put_line('Giving10%raise');
else
_____________________________________________________________________
FocusTrainingServices19
PLSQLNOTES
l_new_salary:=l_salary;
dbms_output.put_line('Nosalaryraise');
endif;
updateemployees
setsalary=l_new_salary
whereemployee_id=p_employee_id;
commit;
end;
/
showerrors
IFconditionTHEN
statements;
[ELSIFconditionTHEN
statements;]
[ELSE
statements;]
ENDIF;
OUTPUT
SQL>@sp21.sql
Procedurecreated.
Noerrors.
SQL>selectsalaryfromemployeeswhereemployee_id=101;
SALARY
17000
SQL>execsp21(101);
Giving10%raise
PL/SQLproceduresuccessfullycompleted.
SQL>selectsalaryfromemployeeswhereemployee_id=101;
SALARY
18700
_____________________________________________________________________
FocusTrainingServices20
PLSQLNOTES
ControlStatement:Case
createorreplaceproceduresp22(p_gradeinvarchar2)
as
CaseStatement
CASEselector
WHENexpression1THENresult1
WHENexpression2THENresult2
...
WHENexpressionNTHENresultN
[ELSEresultN+1;]
END;
ACASEexpressionselectsaresultandreturnsit
l_appraisalvarchar2(100);
begin
l_appraisal:=CASEp_grade
WHEN'A'THEN'Excellent'
WHEN'B'THEN'VeryGood'
WHEN'C'THEN'Good'
ELSE'Nosuchgrade'
END;
DBMS_OUTPUT.PUT_LINE('Grade:'||p_grade||
'Appraisal'||l_appraisal);
end;
/
showerrors
OUTPUT
SQL>@sp22.sql
Procedurecreated.
Noerrors.
SQL>execsp22('C');
Grade:CAppraisalGood
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices21
PLSQLNOTES
ControlStatements:BasicLoop
createorreplaceproceduresp23(p_loop_counterinnumber)
as
BasicLoopconstruct
LOOP
statement1;
...
EXIT[WHENcondition];
ENDLOOP;
Usethebasicloopwhenthestatementsinsidethe
loopmustexecuteatleastonce.
inumber;
begin
i:=1;
loop
dbms_output.put_line(to_char(i));
exitwheni>=p_loop_counter;
i:=i+1;
endloop;
end;
/
showerrors
Basicloopperformrepetativeactions.
Programercanuseexitconditiontoterminatetheloop.
OUTPUT
SQL>@sp23.sql
Procedurecreated.
Noerrors.
SQL>execsp23(5);
1
2
3
4
5
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices22
PLSQLNOTES
ControlStatement:WhileLoop
createorreplaceproceduresp24(p_loop_counterinnumber)
as
WhileLoopconstruct
WHILEconditionLOOP
statement1;
statement2;
...
ENDLOOP;
UsetheWHILEloopiftheconditionhastobe
evaluatedatthestartofeachiteration.
inumber;
begin
i:=1;
whilei<=p_loop_counter
loop
dbms_output.put_line(to_char(i));
i:=i+1;
endloop;
end;
/
showerrors
Whileloopperformsrepetativeactions
untilcontrolingconditionisnolongerTrue.
Theconditionischeckedatstartofeachtransaction.
OUTPUT
SQL>@sp24.sql
Procedurecreated.
Noerrors.
SQL>execsp24(5);
1
2
3
4
5
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices23
PLSQLNOTES
ControlStatement:ForLoop
createorreplaceproceduresp25(p_loop_counterinnumber)
as
ForLoopconstruct
FORcounterIN[REVERSE]
lower_bound..upper_boundLOOP
...
ENDLOOP;
UseaFORloopifthenumberofiterationsisknown.
inumber;
begin
Namingaloopisoptional
<<my_for_loop>>
foriin1..p_loop_counter
loop
sp5(to_char(i),2);
endloopmy_for_loop;
dbms_output.put_line('');
nowthereverseforloop
foriinreverse1..p_loop_counter
loop
dbms_output.put_line(to_char(i));
endloop;
end;
/
showerrors
OUTPUT
SQL>@sp25.sql
Procedurecreated.
Noerrors.
SQL>execsp25(3);
1
2
3
3
2
1
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices24
PLSQLNOTES
InfiniteLoop
createorreplaceproceduresp54
as
Howtowriteaninfiniteloop
begin
while(999=999)
loop
dbms_output.put_line('Hi');
endloop;
while(true)
loop
dbms_output.put_line('Hi');
endloop;
end;
/
showerrors
Asprogramerdidnotmentionedexitcondition,
Proramwillrepeatprintinginfinitelly.
Thisisbadprogramming.
_____________________________________________________________________
FocusTrainingServices25
PLSQLNOTES
COMPOSITEVARIABLES
_____________________________________________________________________
FocusTrainingServices26
PLSQLNOTES
CompositeVariable:Records
createorreplaceproceduresp31
Thisprogramshowshowto
createcompositedatatypes
FirstCompositedatatypeisrecord
as
TYPEemp_sal_recordisRECORD
(last_namevarchar2(20),
salarynumber(10));
emp_salemp_sal_record;
emp_sal_recordcanstore
last_nameandsalaryofemployee
insinglevariable
begin
selectlast_name,salary
intoemp_sal
fromemployees
whereemployee_id=100;
dbms_output.put_line('EmployeeName:'||emp_sal.last_name);
dbms_output.put_line('EmployeesSalary:'||emp_sal.salary);
end;
/
showerrors
CompositeDatatypeRecordsstoresmorethanonedatatypeunder
singlerecord.
OUTPUT:
SQL>@sp31.sql
Procedurecreated.
Noerrors.
SQL>setserveroutputon
SQL>execsp31
EmployeeName:King
EmployeesSalary:24000
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices27
PLSQLNOTES
CompositeDatatype:%rowtype
createorreplaceproceduresp32
Thisprogramshowshowto
createcompositedatatypes
Secondcompositedatatypeis%rowtype
as
emp_recordemployees%rowtype;
emp_recordstores
allvaluesofallcolumns
fromemployeestable
begin
select*
intoemp_record
fromemployees
whereemployee_id=100;
dbms_output.put_line('Name:'||emp_record.last_name);
dbms_output.put_line('DepartmentId:'||
emp_record.department_id);
end;
/
showerrors
%rowtypevariableisusedtostoreallcolumndatatypesin
singlevariable.
OUTPUT:
SQL>@sp32.sql
Procedurecreated.
Noerrors.
SQL>setserveroutputon
SQL>execsp32
Name:King
DepartmentId:90
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices28
PLSQLNOTES
Compositedatatype:Indexbytable
createorreplaceproceduresp33
Thisprogramshowshowto
createcompositedatatypes
ThirdcompositedatatypeisIndexbytable
Thisvariableprovidearraylikeaccesstorows
as
TYPEemp_typeISTABLEOF
employees%rowtype
indexbybinary_integer;
emp_arrayemp_type;
begin
foriin101..104
loop
select*
intoemp_array(i)
fromemployees
whereemployee_id=i;
endloop;
foriinemp_array.FIRST..emp_array.LAST
loop
dbms_output.put_line(emp_array(i).first_name||
''||emp_array(i).last_name);
endloop;
end;
/
showerrors
OUTPUT
SQL>@sp33.sql
Procedurecreated.
Noerrors.
SQL>execsp33
NeenaKochhar
LexDeHaan
AlexanderHunold
BruceErnst
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices29
PLSQLNOTES
CompositeDataType:VariableArray
createorreplaceproceduresp34
Thisprogramshowshowto
Compositedatatype
FourthcompositevariableisVarray
as
typearrisvarray(4)ofregions.region_name%type;
Declarationofvariablearraywitharrayelements=4
arr_1arr;
Initializationofarraycreateemptyarray
l_region_nameregions.region_name%type;
begin
arr_1:=arr();
foriin1..4loop
arr_1.extend(1);
Extendmethodtodefineextracells
selectregion_name
intol_region_name
fromregions
whereregion_id=i;
arr_1(i):=l_region_name;
endloop;
dbms_output.put_line(arr_1.count());
dbms_output.put_line(arr_1(1));
end;
/
showerrors
Thisdatatypeisusefulwhenuserknowsexactlengthforarray
declaration.
OUTPUT
SQL>@sp34.sql
Procedurecreated.
Noerrors.
SQL>execsp34
4
Europe
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices30
PLSQLNOTES
EXPLICITCURSORS
_____________________________________________________________________
FocusTrainingServices31
PLSQLNOTES
ExplicitCursors
createorreplaceproceduresp61
ThisProgramshows
Howtowriteexplicitcursor
Howtoopencursor
Howtofetchdatafromcursor
Howtoclosecursor
as
cursorc1isselectlast_name,salary
fromemployees
wheredepartment_id=20;
Declarationofcursor
l_emp_nameemployees.last_name%type;
l_salemployees.salary%type;
begin
openc1;
OpeningofaCursor
loop
fetchc1intol_emp_name,l_sal;
exitwhenc1%notfound;
FetchingDatafromCursor
dbms_output.put_line(l_emp_name||''||
to_char(l_sal));
endloop;
closec1;
ClosingofCursor
end;
/
showerrors
ForeverySQLstatementexecution,certainareainmemoryis
allocated.
Programercangivenametothatareaandasknownascursor.
Usingcursor,fetchedrowscanbeprocessonebyone.
_____________________________________________________________________
FocusTrainingServices32
PLSQLNOTES
OUTPUT
SQL>!visp61.sql
SQL>@sp61.sql
Procedurecreated.
Noerrors.
SQL>execsp61
Hartstein13000
Fay6000
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices33
PLSQLNOTES
Explicitcursor:FetchingDataintorecords
createorreplaceproceduresp62
ThisProgramshows
Howtofetchdatafromcursorintorecords
as
cursorc1isselect*
fromemployees
wheredepartment_id=50;
CursorDeclaration
rec_c1c1%rowtype;
RecordDeclaration
begin
openc1;
loop
fetchc1intorec_c1;
exitwhenc1%notfound;
FetchingDatafromcursorintorecord
dbms_output.put_line('Name:'||
rec_c1.last_name);
dbms_output.put_line('Salary:'||
rec_c1.salary);
endloop;
closec1;
end;
/
showerrors
OUTPUT
SQL>@sp62.sql
Procedurecreated.
Noerrors.
SQL>execsp62
Name:Hartstein
Salary:13000
Name:Fay
Salary:6000
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices34
PLSQLNOTES
ExplicitCursor:UseofForLoop
createorreplaceproceduresp63
ThisProgramshows
CursorForLoop
as
cursorc1isselect*
fromemployees
wheredepartment_id=20;
begin
forrec_c1inc1loop
ImplicitOpenandFetchoccurs
dbms_output.put_line('Name:'||rec_c1.last_name);
dbms_output.put_line('salary:'||
to_char(rec_c1.last_name));
endloop;
end;
/
showerrors
OUTPUT:
SQL>@sp63.sql
Procedurecreated.
Noerrors.
SQL>execsp63
Name:Hartstein
salary:Hartstein
Name:Fay
salary:Fay
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices35
PLSQLNOTES
ExplicitCursor:Subqueries
createorreplaceproceduresp64
ThisProgramshows
Cursorforloopusingsubqueries
as
l_last_namevarchar2(30);
begin
forl_last_namein(selectlast_namefromemployeeswhere
department_id=20)loop
dbms_output.put_line('Name:'||l_last_name);
endloop;
end;
/
showerrors
OUTPUT:
SQL>@sp64.sql
Procedurecreated.
Noerrors.
SQL>execsp64
Name:Hartstein
Salary:13000
Name:Fay
Salary:6000
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices36
PLSQLNOTES
ExplicitCursor:Passingparameterstocursors
createorreplaceproceduresp65(deptnonumber,jobvarchar2)
ThisProgramshows
Howtopassparameterstocursor
as
cursorc1(l_deptnonumber,l_jobvarchar2)is
selectemployee_id,last_name
fromemployees
wheredepartment_id=l_deptno
andjob_id=l_job;
rec_c1c1%rowtype;
Declarationofcursor
begin
forrec_c1inc1(90,'AD_VP')loop
PassingParamenterstocursor
dbms_output.put_line('Depatment80'||'Job
idisSA_MAN');
dbms_output.put_line('EmployeeID:'||
to_char(rec_c1.employee_id));
dbms_output.put_line('EmployeeName:'||
rec_c1.last_name);
endloop;
openc1(deptno,job);
PassingParamenterstocursor
loop
fetchc1intorec_c1;
exitwhenc1%notfound;
dbms_output.put_line(deptno||'Jobidis'||
job);
dbms_output.put_line('EmployeeID:'||
to_char(rec_c1.employee_id));
dbms_output.put_line('EmployeeName:'||
rec_c1.last_name);
endloop;
closec1;
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices37
PLSQLNOTES
SQL>@sp65.sql
Procedurecreated.
Noerrors.
SQL>execsp65(60,'IT_PROG');
Depatment80JobidisSA_MAN
EmployeeID:101
EmployeeName:Kochhar
Depatment80JobidisSA_MAN
EmployeeID:102
EmployeeName:DeHaan
60JobidisIT_PROG
EmployeeID:103
EmployeeName:Hunold
60JobidisIT_PROG
EmployeeID:104
EmployeeName:Ernst
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices38
PLSQLNOTES
ExplicitCursor:UpdateClause
createorreplaceproceduresp66
ThisProgramshows
TheForUpdateClauseincursor
as
cursorc1is
select*
fromemployees
wheredepartment_id=20
forupdateofsalarynowait;
rec_c1c1%rowtype;
l_new_salnumber;
begin
dbms_output.put_line(rpad('Employee',10)||
rpad('OldSalary',10)||
rpad('NewSalary',10));
openc1;
loop
fetchc1intorec_c1;
exitwhenc1%notfound;
ifrec_c1.salary<7000then
l_new_sal:=rec_c1.salary*1.25;
updateemployeessetsalary=l_new_sal
whereemployee_id=rec_c1.employee_id;
else
l_new_sal:=rec_c1.salary*1.15;
updateemployeessetsalary=l_new_sal
whereemployee_id=rec_c1.employee_id;
endif;
dbms_output.put_line
(rpad(rec_c1.last_name,10)||
rpad(rec_c1.salary,10)||
rpad(l_new_sal,10));
endloop;
closec1;
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices39
PLSQLNOTES
Programercanlockrows
Beforeperforminganyupdateordeleteusingcursor.
Whilecursorisopennoonecanaccessselectedrows.
SQL>@sp66.sql
Procedurecreated.
Noerrors.
SQL>execsp66
EmployeeOldSalaryNewSalary
Hartstein19771.3822737.087
Fay9918.7511406.5625
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices40
PLSQLNOTES
ExplicitCursor:Wherecurrentofclause
createorreplaceproceduresp67
ThisProgramshows
Theuseofwherecurrentofclause
as
cursorc1is
selectemployee_id,salary
fromemployees
wheredepartment_id=20
forupdateofsalarynowait;
l_new_salnumber;
rec_c1c1%rowtype;
begin
dbms_output.put_line(rpad('Employee',10)||
rpad('OldSalary',10)||
rpad('NewSalary',10));
openc1;
loop
fetchc1intorec_c1;
exitwhenc1%notfound;
ifrec_c1.salary<7000then
l_new_sal:=rec_c1.salary*1.25;
updateemployeessetsalary=
l_new_sal
wherecurrentofc1;
else
l_new_sal:=rec_c1.salary*1.25;
updateemployeessetsalary=
l_new_sal
wherecurrentofc1;
endif;
endloop;
closec1;
dbms_output.put_line(rpad(rec_c1.employee_id,10)||
rpad(rec_c1.salary,10)||
rpad(l_new_sal,10));
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices41
PLSQLNOTES
Programercanupdateordelete
onlycurrentrowincursorbydefining
'wherecurrentofclause'
SQL>@sp67.sql
Procedurecreated.
Noerrors.
SQL>execsp67
EmployeeOldSalaryNewSalary
20211406.5614258.2
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices42
PLSQLNOTES
EXCEPTIONS
_____________________________________________________________________
FocusTrainingServices43
PLSQLNOTES
Exceptions:PredefinedExceptions
createorreplaceproceduresp81
ThisProgramshows
HowtohandlePredefineexceptions
as
l_last_nameemployees.last_name%type;
begin
selectlast_name
intol_last_name
fromemployees
whereemployee_id=99999;
dbms_output.put_line(l_last_name);
exception
whenno_data_foundthen
No_data_foundisoneofpredefinedexception
dbms_output.put_line('EmployeeNotexist');
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices44
PLSQLNOTES
Exceptionisakindoferrorthatturminatesuser'sprogram
executionexample'divideby0'.
Oraclehasdefinedapproximately20errorsoccurmostoften.
Knownas'PredefineExceptions'.
OUTPUT
SQL>@sp81.sql
Procedurecreated.
Noerrors.
SQL>execsp82
EmployeeNotexist
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices45
PLSQLNOTES
Exceptions:NonPredefinedExceptions
createorreplaceproceduresp82
Thisprogramshows
Howtohandlenonpredefineexceptions
as
duplicate_keyexception;
PRAGMAEXCEPTION_INIT
(duplicate_key,00001);
begin
insertintodepartmentsvalues(20,'New
Department',200,1800);
commit;
exception
whenduplicate_keythen
dbms_output.put_line('Cannotinsertduplicate
department,departmentalreadyexist');
end;
/
showerrors
NonPredefineexceptionsaredefinedbyoracleserver,
buthasnoname.
UsePragmaexceptiontogivenametorespectiveexception.
SQL>@sp82.sql
Procedurecreated.
Noerrors.
SQL>setserveroutputon
SQL>execsp82
Cannotinsertduplicatedepartment,departmentalreadyexist
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices46
PLSQLNOTES
Exceptions:Others
createorreplaceproceduresp83
as
begin
deletefromdepartments
wheredepartment_id=20;
exceptionwhenothersthen
dbms_output.put_line('InException');
dbms_output.put_line(SQLCODE||SQLERRM);
end;
/
showerrors
ExceptionOthersisusedwhenprogramerdoesnotknow
theoraclenumberassociatedwitherror.
Programercanfinderrorassociatednumberanderrormessage
usingSQLCODE,SQLERRM
OUTPUT
SQL>@sp83.sql
Procedurecreated.
Noerrors.
SQL>execsp83
InException
2292ORA02292:integrityconstraint(HR.EMP_DEPT_FK)violated
childrecord
found
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices47
PLSQLNOTES
Exceptions:UserDefinedExceptions
createorreplaceproceduresp84
as
l_last_nameemployees.last_name%type;
l_salaryemployees.salary%type;
l_new_salfloat;
invalid_raiseexception;
begin
selectlast_name,salary
intol_last_name,l_salary
fromemployees
whereemployee_id=100;
l_new_sal:=l_salary*1.20;
ifl_new_sal>2000then
raiseinvalid_raise;
endif;
exceptionwheninvalid_raisethen
dbms_output.put_line('NotApplicableSalaryraise');
end;
/
showerrors
Programercanintroduceerrorsoncertainconditions.
Thoseerrorsareknownasuserdefineexception.
OUTPUTSQL>@sp84.sql
Procedurecreated.
Noerrors.
SQL>execsp84
NotApplicableSalaryraise
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices48
PLSQLNOTES
Exceptions:RaiseApplicationErrors
createorreplaceproceduresp85
as
l_last_nameemployees.last_name%type;
l_salaryemployees.salary%type;
l_new_salfloat;
new_exceptionexception;
PRAGMAEXCEPTION_INIT(new_exception,20999);
begin
selectlast_name,salary
intol_last_name,l_salary
fromemployees
whereemployee_id=100;
l_new_sal:=l_salary*1.20;
ifl_new_sal>2000then
raise_application_error(20999,'Thisisnotvalid
salaryincrease');
endif;
exceptionwhennew_exceptionthen
dbms_output.put_line('inexception');
dbms_output.put_line(SQLCODE||SQLERRM);
end;
/
showerrors
Programercanissueuserdefineerrormessages
using'raise_application_error'procedure.
Progrmercanassignerrorcodeanderrormessage
fornewexceptions.
Errorcodeshouldbegreaterthan20,000.
OUTPUT
SQL>@sp85.sql
Procedurecreated.
Noerrors.
SQL>execsp85
inexception
20999ORA20999:Thisisnotvalidsalaryincrease
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices49
PLSQLNOTES
Exception:FlowthroughProcedures
createorreplaceproceduresp86(l_employee_idnumber)
Thisprogramshows
Howexceptionhandlingpassesfromoneproceduretoother
as
l_salarynumber;
l_last_namevarchar2(30);
begin
dbms_output.put_line('InouterBlock');
selectsalary
intol_salary
fromemployees
whereemployee_id=l_employee_id;
begin
dbms_output.put_line('InInnerBlock');
selectlast_name
intol_last_name
fromemployees;
end;
exception
whenno_data_foundthen
dbms_output.put_line('Nodatafound');
whentoo_many_rowsthen
dbms_output.put_line('toomanyrows');
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices50
PLSQLNOTES
OUTPUT
SQL>@sp86.sql
Procedurecreated.
Noerrors.
SQL>execsp86(100);
InouterBlock
InInnerBlock
toomanyrows
PL/SQLproceduresuccessfullycompleted.
SQL>execsp86(1111);
InouterBlock
Nodatafound
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices51
PLSQLNOTES
PROCEDURES
_____________________________________________________________________
FocusTrainingServices52
PLSQLNOTES
Procedures:IN,OUTparameters
createorreplaceproceduresp91(l_emp_idinnumber,
l_salaryoutnumber)
ThisProgramsshows
Howtousein,outparameter
as
begin
selectsalary
intol_salary
fromemployees
whereemployee_id=l_emp_id;
end;
/
showerrors
createorreplaceproceduresp92
as
salarynumber;
begin
sp91(100,salary);
salaryusedasoutparameterinsp91
dbms_output.put_line(salary);
end;
/
showerrors
Inparameterusedtopassvaluetoprocedure.
Outparameterisusedtopassvaluefromparameter.
OUTPUT
SQL>@sp91.sql
Procedurecreated.
Noerrors.
SQL>@sp92.sql
Procedurecreated.
Noerrors.
SQL>execsp92
24000
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices53
PLSQLNOTES
Procedures:INOUTParameters
createorreplaceproceduresp93
Thisprogramshows
Howtouseinoutparameter
as
p_phone_novarchar2(20);
begin
p_phone_no:='1234567890';
sp94(p_phone_no);
dbms_output.put_line(p_phone_no);
end;
/
showerrors
createorreplaceproceduresp94
(p_phone_noINOUTvarchar2)
is
begin
p_phone_no:='('||substr(p_phone_no,1,3)||
')'||''||substr(p_phone_no,4,3)||
''||substr(p_phone_no,7);
end;
/
showerrors
INOUTparameterusedtopassvaluetoprocedureandreturnsome
valueinthesamevariable.
i.e.Programerneedonly1variable.
OUTPUT
SQL>@sp94.sql
Procedurecreated.
Noerrors.
SQL>@sp93.sql
Procedurecreated.
Noerrors.
SQL>execsp93
(123)4567890
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices54
PLSQLNOTES
FUNCTIONS
_____________________________________________________________________
FocusTrainingServices55
PLSQLNOTES
Functions
createorreplacefunctionget_dept_name(dept_no
departments.department_id%type)
returnvarchar2
Thisprogramshows
Howtowriteuserdefinefunctions
is
l_dept_namedepartments.department_name%type;
begin
selectdepartment_name
intol_dept_name
fromdepartments
wheredepartment_id=dept_no;
returnl_dept_name;
end;
/
showerrors
Functionsareusedwhenonetaskisexecutedrepeatedly.
Functionsaresimilartoprocedures.
Functionsalwaysreturnssomevaluetocallie.
Afterfunctionsarecreated,
theycanbecalledfromsqlqueryalso.
_____________________________________________________________________
FocusTrainingServices56
PLSQLNOTES
OUTPUT
SQL>@sp10_1.sql
Functioncreated.
Noerrors.
SQL>selectlast_name,department_name
2fromemployeese,departmentsd
3wheree.department_id=d.department_id
4andemployee_id=100;
LAST_NAMEDEPARTMENT_NAME
KingExecutive
SQL>selectlast_name,get_dept_name(department_id)
2fromemployees
3whereemployee_id=100;
LAST_NAMEGET_DEPT_NAME(DEPARTMENT_ID)
KingExecutive
_____________________________________________________________________
FocusTrainingServices57
PLSQLNOTES
PACKAGES
_____________________________________________________________________
FocusTrainingServices58
PLSQLNOTES
Packages
createorreplacepackagecalculatoras
ThisProgramsshowspackagedeclaration/specification
Howtocreatepackagewithpublicprocedures
procedureadd(no1number,no2number);
proceduresubtract(no1number,no2number);
endcalculator;
/
showerrors
Packageusetogrouprelatedprocedurestogether.
InPackagedeclarationdeclarenamesofproceduresandglobal
variables.
InPackagebodywritecodeforthoseprocedures.
createorreplacepackagebodycalculatoris
ThisProgramshows
Howtodeclarebodyofpackage
procedureadd(no1number,no2number)
is
begin
dbms_output.put_line('Additionis:'||to_char(no1+
no2));
endadd;
proceduresubtract(no1number,no2number)
is
begin
dbms_output.put_line('Subtractionis:'||to_char(no1
no2));
endsubtract;
endcalculator;
/
showerrors
_____________________________________________________________________
FocusTrainingServices59
PLSQLNOTES
SQL>@cal_pac.sql
Packagecreated.
Noerrors.
SQL>@cal.sql
Packagebodycreated.
Noerrors.
SQL>execcalculator.add(20,30);
Additionis:50
PL/SQLproceduresuccessfullycompleted.
SQL>execcalculator.subtract(30,40);
Subtractionis:10
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices60
PLSQLNOTES
Package
createorreplacepackagecalculatoras
ThisProgramsshows
Howtocreatepackagewithpublicprocedures
Howtodefineglobalvariableswithdefaultvalues
Howtodefinepublicfunctions
count_addnumber:=0;
count_subtractnumber:=0;
procedureadd(no1number,no2number);
proceduresubtract(no1number,no2number);
functionget_add_countreturnnumber;
functionget_subtract_countreturnnumber;
endcalculator;
/
showerrors
_____________________________________________________________________
FocusTrainingServices61
PLSQLNOTES
createorreplacepackagebodycalculatoris
ThisProgramshows
Howtodefineprivateproceduresinpackagebody
procedureprint(textvarchar2);
functionget_add_countreturnnumber
as
begin
returncount_add;
endget_add_count;
functionget_subtract_countreturnnumber
as
begin
returncount_subtract;
endget_subtract_count;
procedureadd(no1number,no2number)
is
begin
count_add:=count_add+1;
print('Additionis:'||to_char(no1+no2));
endadd;
proceduresubtract(no1number,no2number)
is
begin
count_subtract:=count_subtract+1;
print('Subtractionis:'||to_char(no1no2));
endsubtract;
procedureprint(textvarchar2)
is
begin
dbms_output.put_line(text);
endprint;
endcalculator;
/
showerrors
_____________________________________________________________________
FocusTrainingServices62
PLSQLNOTES
SQL>@cal1.sql
Packagebodycreated.
Noerrors.
SQL>!vimcal1.sql
SQL>@cal_pac1.sql
Packagecreated.
Noerrors.
SQL>@cal1.sql
Packagebodycreated.
Noerrors.
SQL>execcalculator.add(5,2);
Additionis:7
PL/SQLproceduresuccessfullycompleted.
SQL>execcalculator.subtract(10,5);
Subtractionis:5
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices63
PLSQLNOTES
Package:ProcedureOverloading
createorreplacepackagecalculator1as
ThisProgramsshows
Howtocreatepackagewithpublicprocedures
AndProcedureoverloading
procedureadd(no1number,no2number);
procedureadd(no1varchar2,no2varchar2);
procedureadd(no1number,no2number,no3number);
endcalculator1;
/
showerrors
_____________________________________________________________________
FocusTrainingServices64
PLSQLNOTES
createorreplacepackagebodycalculator1is
procedureadd(no1number,no2number)
is
begin
dbms_output.put_line('Additionis:'||to_char(no1+
no2));
endadd;
procedureadd(no1varchar2,no2varchar2)
is
begin
dbms_output.put_line('Concatinationis:'||no1||
no2);
endadd;
procedureadd(no1number,no2number,no3number)
is
begin
dbms_output.put_line('Subtractionis:'||to_char(no1
+no2+no3));
endadd;
endcalculator1;
/
showerrors
ProcedureOverloadingmeansdefiningprocedurewith
samenamebutwithdifferentparameters,datatypes.
Inabovepackageprocedureaddisoverloaded.
_____________________________________________________________________
FocusTrainingServices65
PLSQLNOTES
SQL>execcalculator1.add(10,20);
Additionis:30
PL/SQLproceduresuccessfullycompleted.
SQL>execcalculator1.add('scott','tiger');
Concatinationis:scotttiger
PL/SQLproceduresuccessfullycompleted.
SQL>execcalculator1.add(10,20,30);
Additionis:60
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices66
PLSQLNOTES
ORACLEPACKAGES
_____________________________________________________________________
FocusTrainingServices67
PLSQLNOTES
DefaultPackages:UTL_FILE
createorreplaceproceduresp11_1
ThisProgramshows
HowtosendmailsusingUTL_MAILpackage
as
ora_nonumber;
ora_msgvarchar2(100);
begin
UTL_MAIL.SEND
(sender=>'gaurav@server1.example.com',
recipients=>'gaurav@server1.example.com',
cc=>'mithilesh@server1.example.com',
bcc=>'krunal@server1.example.com',
subject=>'testmail',
message=>'hihowru??'
);
dbms_output.put_line('Messagesendsuccessfully');
exceptionwhenothersthen
ora_no:=sqlcode;
ora_msg:=sqlerrm;
dbms_output.put_line('Messagenotsend');
dbms_output.put_line(ora_no||''||ora_msg);
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices68
PLSQLNOTES
OUTPUT
SQL>@sp11_1.sql
Procedurecreated.
Noerrors.
SQL>execsp11_1
Messagesendsuccessfully
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices69
PLSQLNOTES
DefaultPackages:UTL_FILE
createorreplaceproceduresp11_2
Thisprogramsshow
Howtoreaddatafromtextfile
usingUTL_FILEPackage
as
v_dirvarchar2(200);
SpecifyDirectorynameandpath
v_file_namevarchar2(100);
SpecifyFileName
v_linevarchar2(500)
Acceptfilelinebylineinthisvariable
v_fileUTL_FILE.FILE_TYPE;
FileHandler
begin
v_dir:='/home/gaurav/plsql/';
v_file_name:='utl_file.txt';
v_file:=
UTL_FILE.FOPEN(v_dir,v_file_name,'r');
FileOpeninreadonlymode
loop
begin
UTL_FILE.GET_LINE(v_file,v_line);
exception
whenno_data_foundthen
exit;
end;
dbms_output.put_line(v_line);
endloop;
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices70
PLSQLNOTES
OUTPUT
[gaurav@server1plsql]$catutl_file.txt
hello
howru??
gaurav
OUTPUT
SQL>!vimsp11_2.sql
SQL>@sp11_2.sql
Procedurecreated.
Noerrors.
SQL>execsp11_2
hello
howru??
gaurav
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices71
PLSQLNOTES
DefaultPackages:DBMS_SCHEDULER
createorreplaceproceduresp11_6
Thisprocedureshows
Howtousedefaultpackage
DBMS_SCHEDULERtoschedulesometask
as
orr_codenumber;
orr_msgvarchar2(500);
begin
create_jobisinbuildprocedureinDBMS_SCHEDULER
DBMS_SCHEDULER.CREATE_JOB(
job_name=>'update_sales',
job_type=>'STORED_PROCEDURE',
job_action=>'sp11_4',
start_date=>'20APR1003.10.00.000000000PM
ASIA/CALCUTTA',
repeat_interval=>'FREQ=SECONDLY;INTERVAL=10',
end_date=>'20APR1003.11.00.000000000PM
ASIA/CALCUTTA',
comments=>'Mynewjob');
exceptionwhenothersthen
orr_code:=sqlcode;
orr_msg:=sqlerrm;
dbms_output.put_line(orr_code||''||orr_msg);
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices72
PLSQLNOTES
OUTPUT
15:04:48SQL>truncatetabletest_sch;
Tabletruncated.
15:04:57SQL>@sp11_6.sql
Procedurecreated.
Noerrors.
15:05:01SQL>execsp11_6
PL/SQLproceduresuccessfullycompleted.
15:05:06SQL>exec
dbms_scheduler.set_scheduler_attribute('MAX_JOB_SLAVE_PROCESSES',
2);
requiresmanageschedulerprivilege
PL/SQLproceduresuccessfullycompleted.
15:05:22SQL>execdbms_scheduler.enable('update_sales');
enablethejob
PL/SQLproceduresuccessfullycompleted.
15:05:43SQL>select*fromtest_sch;
norowsselected
15:07:31SQL>selectcount(*)fromtest_sch;
COUNT(*)
0
15:09:41SQL>/
COUNT(*)
100
_____________________________________________________________________
FocusTrainingServices73
PLSQLNOTES
15:10:04SQL>/
COUNT(*)
200
15:10:14SQL>/
COUNT(*)
300
15:10:27SQL>/
COUNT(*)
400
15:10:37SQL>/
COUNT(*)
500
15:10:46SQL>/
COUNT(*)
600
15:10:53SQL>/
COUNT(*)
600
_____________________________________________________________________
FocusTrainingServices74
PLSQLNOTES
DYNAMICSQL
_____________________________________________________________________
FocusTrainingServices75
PLSQLNOTES
DynamicSql
createorreplaceproceduresp12_1(l_table_namevarchar2)
Thisprogramshows
Howtobuilddynamicsqlqueries.
as
sql_queryvarchar2(50);
l_countnumber;
begin
sql_query:='selectcount(*)from'||l_table_name;
executeimmediatesql_queryintol_count;
Writesqlcommandinavarchar2variable
Andthenusecommand'executeimmediate'
Acceptreturingvalueinappropriatevariable
dbms_output.put_line(l_count);
end;
/
showerrors
OUTPUT
SQL>@sp12_1.sql
Procedurecreated.
Noerrors.
SQL>execsp12_1('REGIONS');
4
PL/SQLproceduresuccessfullycompleted.
_____________________________________________________________________
FocusTrainingServices76
PLSQLNOTES
TRIGGERS
_____________________________________________________________________
FocusTrainingServices77
PLSQLNOTES
Trrigers
createorreplacetriggerchk_emp_sal
Thisprogramsshows
Howtodeclaretriggers
foreachrow
beforeinsertorupdate
ofsalary
onemployees
foreachrow
declare
v_errorVARCHAR2(2000);
begin
if:new.salary>25000then
v_error:=:old.first_name||'cannothavethatmuch!';
raise_application_error(20999,v_error);
endif;
end;
/
showerrors
_____________________________________________________________________
FocusTrainingServices78
PLSQLNOTES
OUTPUT
SQL>@14_1.sql
Triggercreated.
Noerrors.
SQL>insertinto
employees(EMPLOYEE_ID,LAST_NAME,EMAIL,HIRE_DATE,JOB_ID,SALARY)
2values(215,'Bhide','abc@gmail.com',sysdate,'IT_PROG',26000);
insertinto
employees(EMPLOYEE_ID,LAST_NAME,EMAIL,HIRE_DATE,JOB_ID,SALARY)
*
ERRORatline1:
ORA20999:cannothavethatmuch!
ORA06512:at"HR.CHK_EMP_SAL",line7
ORA04088:errorduringexecutionoftrigger'HR.CHK_EMP_SAL'
_____________________________________________________________________
FocusTrainingServices79
PLSQLNOTES
Triggers:Updating,Inserting,Deleting
createorreplacetriggertrig_example
beforeinsertordeleteorupdateontrig_eg
foreachrow
declare
ChangeTypevarchar2(10);
begin
/*Use'I'foranINSERT,'D'forDELETE,and'U'forUPDATE.*/
ifinsertingthen
ChangeType:='I';
elsifupdatingthen
ChangeType:='U';
else
ChangeType:='D';
endif;
insertintochanges_recordvalues(ChangeType,USER,SYSDATE);
endtrig_example;
/
showerrors
_____________________________________________________________________
FocusTrainingServices80
PLSQLNOTES
OUTPUT
SQL>@sp14_2.sql
Triggercreated.
Noerrors.
SQL>select*fromCHANGES_RECORD;
norowsselected
SQL>insertintotrig_egvalues(1,'aaa');
1rowcreated.
SQL>insertintotrig_egvalues(2,'bbb');
1rowcreated.
SQL>updatetrig_egsetname='xxxx'whereid=2;
1rowupdated.
SQL>deletefromtrig_egwhereid=2;
1rowdeleted.
SQL>select*fromCHANGES_RECORD;
CHANGEUSER_NAMECHANGE_DA
IGAURAV18APR10
IGAURAV18APR10
UGAURAV18APR10
DGAURAV18APR10
SQL>select*fromtrig_eg;
IDNAME
1aaa
_____________________________________________________________________
FocusTrainingServices81