Extension to SQL: View, Triggers, Cursor

Extension to SQL: View, Triggers, Cursor

ExtensionExtension toto SQL:SQL: View,View, Triggers,Triggers, CursorCursor SSSS ChungChung 1 ViewsViews (Virtual(Virtual Tables)Tables) inin SQLSQL ConceptConcept ofof aa viewview inin SQLSQL SingleSingle tabletable derivedderived fromfrom otherother tablestables ConsideredConsidered toto bebe aa virtualvirtual tabletable 2 SpecificationSpecification ofof ViewsViews inin SQLSQL CREATECREATE VIEWVIEW commandcommand GiveGive TableTable (View)(View) name,name, listlist ofof attributeattribute namesnames forfor thethe ViewView (table),(table), andand aa QueryQuery toto specifyspecify thethe contentscontents ofof thethe ViewView 3 AlteringAltering ExistingExisting ViewView ReplaceReplace ViewView Existing_View_NameExisting_View_Name AsAs SelectSelect …… FromFrom …… WhereWhere ……;; ReplaceReplace ViewView Works_On1Works_On1 AsAs SelectSelect FnameFname ,, LnameLname ,, PnoPno ,, PnamePname ,, HoursHours FromFrom Employee,Employee, Works_OnWorks_On ,, ProjectProject WhereWhere SsnSsn == EssnEssn andand PnoPno == PnumberPnumber 4 SpecificationSpecification ofof ViewsViews inin SQLSQL (cont(cont ’’d.)d.) SpecifySpecify SQLSQL queriesqueries onon aa viewview ViewView alwaysalways upup --toto --datedate ResponsibilityResponsibility ofof thethe DBMSDBMS andand notnot thethe useruser DROPDROP VIEWVIEW commandcommand DisposeDispose ofof aa viewview 5 ViewsViews Students ( sid , name, address, gpa ) Completed ( sid , course , grade) A view is a query stored in the database – Think of it as a table definition for future use Example view definition: CREATE VIEW GS tudents AS SELECT * FROM Students WHERE gpa >= 2.5 Views can be used like base tables , in any query or in any other view. Like a Macro. Different from Insert INTO. 6 ExampleExample viewview use:use: simplersimpler queriesqueries SupposeSuppose youyou wantwant toto retrieveretrieve goodgood studentsstudents whowho havehave completedcompleted CIS430.CIS430. GSGS tudentstudents ((sidsid ,, name,name, address,address, gpagpa )) SELECTSELECT S.name,S.name, S.phoneS.phone FROMFROM GstudentsGstudents SS INNERINNER JOINJOIN CompletedCompleted CC ONON S.sidS.sid == C.sidC.sid WHEREWHERE C.courseC.course == ‘‘CIS430CIS430 ’’;; ItIt ’’ss easiereasier toto writewrite thethe queryquery usingusing thethe view.view. 7 ViewsViews forfor SecuritySecurity ThisThis isis thethe studentstudent tabletable withoutwithout thethe gpagpa fieldfield toto hidehide gpagpa toto anyany useruser inin DB.DB. CREATECREATE VIEWVIEW SstudentsSstudents ASAS SELECTSELECT sidsid ,, name,name, addressaddress FROMFROM studentsstudents 8 ViewsViews forfor ExtensibilityExtensibility An old company ’s database includes a table: Part ( PartID , Name, Weight) Weight is stored in pounds The company is purchased by a new firm that uses metric weights The two databases, old and new , must be integrated and use Kg. But there ’s lots of old software using pounds. Solution: views! 9 ViewsViews forfor extensibilityextensibility (( ctdctd )) Solution:Solution: 1.1. BaseBase tabletable withwith kilograms:kilograms: NewPartNewPart forfor newnew integratedintegrated companycompany 2.2. CREATECREATE VIEWVIEW PartPart ASAS SELECTSELECT PartIDPartID ,, Name,Name, 2.2046*2.2046* WeightWeight FROMFROM NewPartNewPart ;; 3.3. OldOld programsprograms stillstill callcall thethe tabletable ““PartPart ”” 10 ViewView UpdateUpdate andand InlineInline ViewsViews ClauseClause WITHWITH CHECKCHECK OPTIONOPTION MustMust bebe addedadded atat thethe endend ofof thethe viewview definitiondefinition ifif aa viewview isis toto bebe updatedupdated InIn --lineline viewview (dynamic(dynamic Table)Table) DefinedDefined inin thethe FROMFROM clauseclause ofof anan SQLSQL queryquery 11 ViewView Implementation,Implementation, ViewView Update,Update, andand InlineInline ViewsViews ComplexComplex problemproblem ofof efficientlyefficiently implementingimplementing aa viewview forfor queryingquerying QueryQuery modificationmodification approachapproach ModifyModify viewview queryquery intointo aa queryquery onon underlyingunderlying basebase tablestables Disadvantage:Disadvantage: inefficientinefficient forfor viewsviews defineddefined viavia complexcomplex queriesqueries thatthat areare timetime --consumingconsuming toto executeexecute 12 ViewView ImplementationImplementation ViewView materializationmaterialization approachapproach PhysicallyPhysically createcreate aa temporarytemporary viewview tabletable whenwhen thethe viewview isis firstfirst queriedqueried KeepKeep thatthat tabletable onon thethe assumptionassumption thatthat otherother queriesqueries onon thethe viewview willwill followfollow RequiresRequires efficientefficient strategystrategy forfor automaticallyautomatically updatingupdating thethe viewview tabletable whenwhen thethe basebase tablestables areare updatedupdated 13 ViewView ImplementationImplementation (cont(cont ’’d.)d.) IncrementalIncremental updateupdate strategiesstrategies DBMSDBMS determinesdetermines whatwhat newnew tuplestuples mustmust bebe inserted,inserted, deleted,deleted, oror modifiedmodified inin aa materializedmaterialized viewview tabletable 14 ProblemProblem withwith views:views: updateupdate Views cannot always be updated unambiguously. Consider EmpEmp ((((empidempid ,, enameename ,, address,address, deptiddeptid )))) DeptDept (( deptiddeptid ,, dnamedname )))) CREATECREATE VIEWVIEW EMPDEPTEMPDEPT ASASASAS SELECTSELECT enameename ,, dnamedname FROMFROM EmpEmp InnerJOINInnerJOIN DeptDept ONON Emp.deptidEmp.deptid ====Dept.deptidDept.deptid ;;;; EMPDEPTEMPDEPT enameename dnamedname jimjimjimjim shoeshoe joejoejoejoe suitsuit I want to delete ( jim , shoe) from EMPDEPT. Can I do that? 15 ViewView UpdateUpdate ViewView cancan bebe updatedupdated ifif ––ItIt isis defineddefined onon aa singlesingle basebase tabletable ––UsingUsing onlyonly SelectionSelection andand ProjectionProjection ––NoNo AggregatesAggregates ––NoNo DISTINCTDISTINCT 16 ViewView UpdateUpdate andand InlineInline ViewsViews UpdateUpdate onon aa viewview defineddefined onon aa singlesingle tabletable withoutwithout anyany aggregateaggregate functionsfunctions CanCan bebe mappedmapped toto anan updateupdate onon underlyingunderlying basebase tabletable ViewView involvinginvolving joinsjoins cancan NOTNOT bebe updatedupdated OftenOften notnot possiblepossible forfor DBMSDBMS toto determinedetermine whichwhich ofof thethe updatesupdates isis intendedintended 17 LevelsLevels ofof AbstractionAbstraction External view; user and data designer ES 1 ES 2 ES 3 Logical storage; data designer Conceptual Schema Physical Schema Physical storage; DBA 18 PhysicalPhysical SchemaSchema TheThe physicalphysical schemaschema isis aa descriptiondescription ofof howhow thethe datadata isis physicallyphysically storedstored inin thethe database.database. ItIt includesincludes –– WhereWhere thethe datadata isis locatedlocated –– FileFile structuresstructures –– AccessAccess methodsmethods –– IndexesIndexes TheThe physicalphysical schemaschema isis managedmanaged byby thethe DBA.DBA. 19 ConceptualConceptual SchemaSchema TheThe conceptualconceptual schemaschema -- aa logicallogical descriptiondescription ofof howhow thethe datadata isis stored.stored. -- ItIt consistsconsists ofof thethe schemasschemas wewe havehave describeddescribed withwith CREATECREATE TABLETABLE statements.statements. ItIt isis managedmanaged byby thethe datadata designer.designer. 20 ExternalExternal SchemasSchemas EachEach externalexternal schemaschema isis aa combinationcombination ofof basebase tablestables andand views,views, tailoredtailored toto thethe needsneeds ofof aa singlesingle user.user. ItIt isis managedmanaged byby thethe datadata designerdesigner andand thethe user.user. 21 DataData IndependenceIndependence AA databasedatabase modelmodel possessespossesses datadata independenceindependence ifif applicationapplication programsprograms areare immuneimmune toto changeschanges inin thethe conceptualconceptual andand physicalphysical schemas.schemas. WhyWhy isis thisthis important?important? EverythingEverything changes.changes. HowHow doesdoes thethe relationalrelational modelmodel achieveachieve logicallogical (conceptual)(conceptual) datadata independence?independence? –– ThroughThrough viewsviews –– IfIf thethe conceptualconceptual schemaschema changes,changes, aa viewview cancan bebe defineddefined toto preservepreserve existingexisting applicationsapplications 22 DataData IndependenceIndependence (( ctdctd .).) How does the relational model achieve physical data independence? 1. Conceptual level contains no physical info 2. SQL can program against the conceptual level – Earlier DBMSs (network, hierarchical) did not have these properties. – Their languages had physical properties embedded in them. That is the primary reason for the success of the relational model 23 Views:Views: SummarySummary AA viewview isis aa storedstored queryquery definitiondefinition ViewsViews cancan bebe veryvery usefuluseful –– EasierEasier queryquery writing,writing, security,security, extensibilityextensibility ButBut viewsviews cannotcannot bebe unambiguouslyunambiguously updatedupdated ThreeThree levelslevels ofof abstractionabstraction inin aa relationalrelational DBMSDBMS –– YieldsYields datadata independence:independence: logicallogical andand physicalphysical 24 SpecifyingSpecifying ConstraintsConstraints asas AssertionsAssertions andand ActionsActions asas TriggersTriggers CREATECREATE ASSERTIONASSERTION SpecifySpecify additionaladditional typestypes ofof constraintsconstraints outsideoutside

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    66 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us