Upload
tranthuy
View
228
Download
0
Embed Size (px)
Citation preview
Hacettepe UniversityComputerEngineeringDepartment
ProgrammingtheDatabase
BBM471DatabaseManagementSystems
Dr.Fuat Akal
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
Today’sLecture
1. StoredProcedures
2. Functions
3. Cursors
4. Triggers
5. DynamicSQL
2
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
StoredProcedures
• AstoredprocedurecontainsasequenceofSQLcommandsstoredinthedatabasecatalogsothatitcanbeinvokedlaterbyaprogram
• Storedproceduresaredeclaredusingthefollowingsyntax(IrefertoMySQLinthispresentation):
CreateProcedure <proc-name>(param_spec1,param_spec2,…,param_specn )
begin-- executioncode
end;
whereeachparam_spec isoftheform:[in|out|inout]<param_name><param_type>
• inmode:allowsyoutopassvaluesintotheprocedure,• outmode:allowsyoutopassvaluebackfromproceduretothecallingprogram
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
ExampleStoredProcedure:Definition
4
Supposewewanttokeeptrackofthetotalsalariesofemployeesworkingforeachdepartment
Weneedtowriteaproceduretoupdatethesalariesinthedeptsal table
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
CreatetheStoredProcedure
1. Changethedelimiter(i.e.,terminatingcharacter)ofSQLstatementfromsemicolon(;)tosomethingelse(e.g.,//)
2. DefineaprocedurecalledupdateSalary whichtakesasinputadepartmentnumber.
3. ThebodyoftheprocedureisanSQLcommandtoupdatethetotalsalary columnofthedeptsal table.
4. Terminatetheproceduredefinitionusingthedelimiteryouhaddefinedinstep1(//)
5. Changethedelimiterbacktosemicolon(;)
5
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
CalltheStoredProcedure
6
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
DebuggingaStoredProcedure
• Usingaselectstatement• SELECT ‘Comment’; -- PuttheliteralCommentouttoconsole
• Insertintoatable• Puttingthecurrenttimeanddatestampintoacolumnwiththecomment.
• Logmessagestoanoutputfile• Select <time_stamp>, ‘Comment’ into outfile ‘<file_name>’;
• Whichmightbeblockedbythesecuritymechanism.
7
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
ProgrammingStructures
• Googlefor“XXXreferencemanual”• XXXàMySQL,SQLServer,Oracle,Sybase,etc.
• e.g.,tolocateIFstatement,clickon• FunctionsandOperators
• ControlFlowFunctions
8
https://dev.mysql.com/doc/refman/8.0/en/
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
DatabaseCursors
• Adatabasecursor isacontrolstructurethatenablestraversalovertherecordsinadatabase.
• Cursors facilitatesubsequentprocessinginconjunctionwiththetraversal,suchasretrieval,additionandremovalofdatabase records.
• Acursor can'tbeusedbyitself.Itisanessentialcomponentinstoredprocedures.
9
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
ExampleCursor
10
Drop the old procedure
Use cursor to iterate the rows
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
CursorExample(OraclePl/SQL)
11
DECLAREPi constant NUMBER(8,7) := 3.1415926;area NUMBER(14,2);cursor rad_cursor is select * from RAD_VALS;rad_val rad_cursor%ROWTYPE;
BEGINopen rad_cursor;fetch rad_cursor into rad_val;area:=pi*power(rad_val.radius,2);insert into AREAS values (rad_val.radius, area);close rad_cursor;
END;
Rad_cursor
fetch
Rad_val
Radius AreaAREAS
3 28.27
VALSRAD_
radius
3
6
8
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
SelectForUpdate
• Cursorscanalsobeusedtoperformupdates
cursor<cname>is<select-statement>forupdate;
• Selectstatementshouldinvolveonlyonedatabasetable
update<table-name>set<set-clause>wherecurrentof<cname>;
deletefrom<table-name>wherecurrentof<cname>;
12
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
Functions
• Functionsreturnsomevalueandaredeclaredusingthefollowingsyntax:
function <function-name>(param_spec1,…,param_speck)
returns<return_type>[not]deterministic
Begin-- executioncode
end;
whereparam_spec is:
[in|out|inout]<param_name><param_type>
13
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
ExampleFunction
14
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
FunctionCall
15
Hacettepe UniversityComputerEngineeringDepartment
Triggers
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
WhatisaTrigger?
• Atrigger isastatementthatisexecutedautomaticallybythesystemasasideeffectofamodificationtothedatabase.
• Todesignatriggermechanism,wemust:• Specifytheconditionsunderwhichthetriggeristobeexecuted.• Specifytheactionstobetakenwhenthetriggerexecutes.
• TriggersintroducedtoSQLstandardinSQL:1999,butsupportedevenearlierusingnon-standardsyntaxbymostdatabases.
17
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
Triggervs.Vendors
• AvailableinmostenterpriseDBMSs(Oracle,IBMDB2,MSSQLserver)andsomepublicdomainDBMSs(Postgres,MySQL)
• SomevendorDBMSpermitnativeextensionstoSQLforspecifyingthetriggers• e.g.PL/SQLinOracle,TransactSQLinMSSQLServer
• SomeDBMSalsoallowuseofgeneralpurposeprogramminglanguageinsteadofSQL
• e.g.JavainOracle,C#/VBinSQLServer
• SomeDBMSextendthetriggersbeyondtables• forexamplealsotoviewsasinOracle
18
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TypesofTriggers
• Howmanytimesshouldthetriggerbodyexecutewhenthetriggeringeventtakesplace?
• Perstatement: thetriggerbodyexecutesonceforthetriggeringevent.Thisisthedefault.
• Foreachrow: thetriggerbodyexecutesonceforeachrowaffectedbythetriggeringevent.
• Whenthetriggercanbefired• RelativetotheexecutionofanSQLDMLstatement(beforeorafterorinsteadofit)
• Exactlyinasituationdependingonspecificsystemresources(e.g.signalfromthesystemclock,expiringtimer,exhaustingmemory)
19
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggeringEventsandActionsinSQL
• Triggeringeventcanbeinsert,delete orupdate
• Valuesofattributesbeforeandafteranupdatecanbereferenced• referencingoldrowas :fordeletesandupdates• referencingnewrowas:forinsertsandupdates
• Triggerscanbeactivatedbeforeanevent,whichcanserveasextraconstraints.E.g.convertblankstonull.
createtriggersetnull-triggerbeforeupdateonrreferencingnewrowasnrowforeachrowwhennrow.phone-number=‘‘setnrow.phone-number=null
20
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
FiringSequenceofDatabaseTriggersonaSingleRow
21
DEPTNO10203040
DNAMEACCOUNTINGRESEARCHSALESOPERATIONS
LOCNEW YORKDALLASCHICAGOBOSTON
DEPT table BEFORE statement trigger
BEFORE row triggerAFTER row trigger
AFTER statement trigger
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
FiringSequenceofDatabaseTriggersonMultipleRows
22
EMPNO
7839
7698
7788
ENAME
KING
BLAKE
SMITH
DEPTNO
30
30
30
BEFORE statement trigger
BEFORE row triggerAFTER row triggerBEFORE row triggerAFTER row triggerBEFORE row triggerAFTER row trigger
AFTER statement trigger
EMP table
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggerExample- 1
• Wewanttocreateatriggertoupdatethetotalsalaryofadepartmentwhenanewemployeeishired
23
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggerExample- 1
• Createatriggertoupdatethetotalsalaryofadepartmentwhenanewemployeeishired
• Thekeyword“new”referstothenewrowinserted
24
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment 25
totalsalary increases by 90K
totalsalary did not change
TriggerExample- 1
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggerExample- 2
• Atriggertoupdatethetotalsalaryofadepartmentwhenanemployeetupleismodified:
26
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggerExample- 2
27
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggerExample- 3
• Atriggertoupdatethetotalsalaryofadepartmentwhenanemployeetupleisdeleted:
28
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
TriggerExample- 3
29
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
UsingDatabaseTriggersforInformationProcessing
• AuditingTableOperations• eachtimeatableisaccessedauditinginformationisrecordedagainstit
• TrackingRecordValueChanges• eachtimearecordvalueischangedthepreviousvalueisrecorded
• ProtectingDatabaseReferentialIntegrity:ifforeignkeypointstochangingrecords• referentialintegritymustbemaintained
• MaintenanceofSemanticIntegrity• e.g.whenthefactoryisclosed,allemployeesshouldbecomeunemployed
• StoringDerivedData• e.g.thenumberofitemsinthetrolleyshouldcorrespondtothecurrentsessionselection
• SecurityAccessControl• e.g.checkinguserprivilegeswhenaccessingsensitiveinformation
30
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
WhenNotToUseTriggers
• Triggerswereusedearlierfortaskssuchas• maintainingsummarydata(e.g.totalsalaryofeachdepartment)• Replicatingdatabasesbyrecordingchangestospecialrelations(calledchange ordeltarelations)andhavingaseparateprocessthatappliesthechangesovertoareplica
• Therearebetterwaysofdoingthesenow:• Databasestodayprovidebuiltinmaterializedviewfacilitiestomaintainsummarydata• Databasesprovidebuilt-insupportforreplication
• Encapsulationfacilitiescanbeusedinsteadoftriggersinmanycases• Definemethodstoupdatefields• Carryoutactionsaspartoftheupdatemethodsinsteadofthroughatrigger
31
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
DynamicSQL
Sometimesyouneedtooperateagainstatableorcolumnsthatarenotknownatcompiletime.
CREATE DEFINER=`root`@`localhost` PROCEDURE `dynamic`(in tableName varchar(40))begin
set @statement = concat('select * from ', tableName);prepare stmt from @statement;execute stmt;set @statement = concat('select count(*) from ', tableName, ' into @count');prepare stmt from @statement;execute stmt;select concat('Count was: ', @count, ' from table: ', tableName);deallocate prepare stmt;
end
32
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
Summary
• ItisnotpossibletoperformalltasksbyusingasingleSQLstatement
• Sometimesyouneedtoimplementthebusinesslogicatthedatabaseside
• Thereyoucanusestoredprocedures,functions,cursors,trigger,etc.• Therearefewmorestructuresnotcoveredinthislecture
33
Hacettepe UniversityComputerEngineeringDepartmentHacettepe UniversityComputerEngineeringDepartment
Acknowledgements
Thecoursematerialusedforthislectureismostlytakenand/oradoptedfrom:
• www.cse.msu.edu/~pramanik/teaching/courses/cse480/14s/lectures/12/lecture13.pptbySaktiPramanik atMichiganStateUniversity
• DatabaseSystemConcepts,Avi Silberschatz,HenryF.Korth,S.Sudarshan
34