123 Pages

chPL_SQLPart1

Course: IS 620, Spring 2012
School: UMBC
Rating:
 
 
 
 
 

Word Count: 5382

Document Preview

IntroductiontoPL/SQL IS620 AdvancedDatabaseProjects 1 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n Basicstructure VariablesandAssignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 2 IsSQLPowerfulEnough? n DoyouneedtowritemultipleSQLstatementsforatask? n E.g., to transfer a...

Register Now

Unformatted Document Excerpt

Coursehero >> Maryland >> UMBC >> IS 620

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
IntroductiontoPL/SQL IS620 AdvancedDatabaseProjects 1 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n Basicstructure VariablesandAssignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 2 IsSQLPowerfulEnough? n DoyouneedtowritemultipleSQLstatementsforatask? n E.g., to transfer a certain amount from your checking account to saving, only transfer when there is enough balanceinchecking. n DoesSQLhavevariables,loops,ifthenelse? n HowcanothersusetheSQLstatementsyoudeveloped? 3 WhyPL/SQL n Real life example: E.g., a credit bureau provides a credit scoringservice. n n n n The company collects personal financial data from credit card companies,banks,.,andstorethedatainadatabase Customerscanaskthecreditscoreofsomeperson Thescoreiscomputedfromthedatausingacomplexformula(a topcommercialsecret) CanwejustuseSQL? What'smy creditscore 700! 4 WhyPL/SQL n Solution1:embedSQLintoaprocedurelanguagesuchasJAVAorC n n n n E.g.,JDBC,ODBC ClientprogramsendsSQLtoDBserverandgetsbackintermediateresults Clientprogramthencomputescreditscore Problems? JAVA program What'smy creditscore 700! SQL Intermediate results 5 WhyPL/SQL n n OracleProcedureLanguage/SQL n SQL+procedurelanguagefeaturessuchasvariables,IFTHEN,loop, functionorprocedure,etc. n AnamedPL/SQLprogramisstoredwithinthedatabase,andcanbeused byotherusers Benefits n n n n Communicationcost Portability Security Learningcurve What'smycreditscore?CallaPL/SQLfunction ondatabaseserver 700! 6 WhyPL/SQL n OracleProcedureLanguage/SQL n Downside? n n WhichDMBStouse? DoesPL/SQLprovideaGUI? What'smycreditscore?CallaPL/SQLfunction ondatabaseserver 700! 7 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n Basicstructure VariablesandAssignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 8 AnonymousPL/SQLPrograms n n n n n Programhasnoname CodeisNOTstoredindatabase(discardedafter execution) Codecanbestoredasascriptfileinlocalfile system,butyouhavetomanuallysave&loadit. Cannotacceptorpassparametervalues Whendoyouwanttouseanonymousprogram? 9 NamedPL/SQLPrograms n Stored n n n n n Ascompiledobjectsindatabase(functions, procedures) Cantakeparametersasinput Canbecalledbyotherprograms Canbeexecutedbyotherusers Whendoyouwanttousenamedprogram? 10 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n Basicstructure VariablesandAssignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 11 AnonymousPL/SQLSubprogram BasicStructure: Declare Declarationofvariables Begin statements Exception handleexceptions End; n Thesubprogramisunnamedandcanbeusedonlyonce n Declarationisoptional n Exceptionsectionisalsooptional n Musthavebeginend; n 12 ASimplePL/SQLExample DECLARE foovarchar(20); BEGIN foo:='Hello,world!'; dbms_output.put_line(foo); END; 13 PL/SQLProgramLines Mayspanmultipletexteditorlines Eachlineendswithasemicolon Textisnotcasesensitive Note:quoteinPowerPointandWordmaynot berecognizedinPL/SQL,usenotepad 14 CommentStatements Blockofcommentsaredelimitedwith/**/ /* <comment that spans more than one line of code> */ 4 Singlecommentlinestartswith2hyphens -- comment on a single line 15 FirstPL/SQLProgram DECLARE foovarchar(20); BEGIN foo:='Hello,world!'; dbms_output.put_line(foo); END 16 DisplayingPL/SQLOutputin SQL*Plus NormallyPL/SQLisusedwithotherOracle utilitiessuchasformsorreports YouwilllearntousePL/SQLinSQL*Plus CommandtoenableoutputfromPL/SQL programs: SET SERVEROUTPUT ON; 4 You need to turn on serveroutput every time you log in 17 DisplayingPL/SQLOutputin SQL*Plus UsingDBMS_OUTPUTpackagetooutput DBMS_OUTPUT.PUT_LINE(item); Item can be either varchar or number, integer, E.g. Declare greeting varchar(50) := 'Hello World'; x integer := 10; begin dbms_output.put_line('Hello World'); dbms_output.put_line(greeting); dbms_output.put_line(x); dbms_output.put_line(10); End; 18 DisplayingPL/SQLOutputin SQL*Plus n n DBMS_OUTPUT.PUT(iteminvarcharor number); outputtheitemwithoutendofline DBMS_OUTPUT.NEW_LINE; outputanendofline 19 Exercises WriteaPL/SQLprogramtoprint'Thisismyfirst PL/SQLprogram' 20 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n Basicstructure VariablesandAssignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 21 Variables Typicallyusedtostoresomevalues n Stepsusingavariable Declare variable_namedata_type; Begin variable_name:=value;assignvaluetoavariable usevariables(e.g.,inassignment,output,SQL,etc.) dbms_output.put_line(variable_name); End; n E.g. Declarexnumber; Begin X:=10; dbms_output.put_line('xis'||x); End; 22 Variables n n n n n Namingconventions Declarationandscope Assignment Datatypes Assignmentofcompositedatatype 23 NamingConventions VariablenamesmustfollowtheOraclenaming standard:startwithaletter,followedbyletter,digit,or _(space,notallowed) n Arethefollowingnamesvalid?(separatedby comma) empname1,empname1,1emp_name,emp_name1, empname1, n n Makevariablenamesdescriptive,andseparate wordswithunderscores n Example:current_s_id 24 Declaration n Syntaxfordeclaringavariable: variable_namedata_type_declaration; n Example:current_s_idNUMBER; 25 Scope Scope:therangewherethevariableisvalid Validinthebeginendblockafteritisdeclared n E.g., Declarexnumber; Begin X:=10; End; xisnotvalidoutsidetheprogram 26 AssignmentStatements(Morelater) Assignmentoperator::= Variablebeingassignedtoanewvalueison leftsideofassignmentoperator Newvalueisonrightsideofoperator student_name := 'John Miller'; student_name := current_student; 27 Exercise n Declareavariablegreeting,andgiveitvalue 'Thisismysecondpl/sqlprogram',andprint thevariableonscreen. 28 PL/SQLDataTypes n n AllSQLdatatypecanbeusedinPL/SQL Scalar n n Composite n n Varray,record,table Reference n n Asinglevalue,e.g.,number,integer,varchar Pointers:refcursor,refobject_type LOB n largeobject:clob,blob,bfile 29 ScalarDataTypes n n n n n n VARCHAR:variablelength. E.g.,namevarchar(20) CHAR:fixedlength.E.g.,zipchar(9) INTEGER:e.g.,idinteger; NUMBER:e.g.,balancenumber; FLOAT,REAL:e.g.,amountfloat; BOOLEAN:e.g.,validboolean:=TRUE; 30 Date&TimeTypes DATE,Timestamp:sameasinSQL Declare start_datedate; Checkouttimestamp; Begin n start_date:=date'200525'; Checkout:=timestamp'2005020517:00:53.00'; End; 31 CommonErrors n n Tooshortlengthforcharandvarchartype Forgettoputdateandtimestampprefixfor dateandtimestampvalues 32 SelectCurrentTime/Date InPL/SQLprogram,youjustneedtousesystemvariable systimestamp E.g., declare current_timetimestamp; Current_datedate; begin current_time:=systimestamp; Current_date:=sysdate; dbms_output.put_line(current_time+interval'1'hour); Dbms_output.put_line(current_date+interval'1'day); end; n 33 Exercise n Printoutcurrenttimeandoneweekfrom currenttime 34 CompositeDataTypes n n n Referringtodatabasecolumnandrowtypes RECORD(notrequired) VARRAY,nestedtable,associatedarray(not required) 35 ReferringtoColumnDataType n UsedatatypeofaDBcolumn n n Tablename.columnname%TYPE:samedatatypeasthat column Examples Declare e_nameemp.ename%type; Begin e_name:='john'; Insertintoempvalues(5,e_name,2,date'200691',55000); End; n Benefits? 36 Exercise n Createthefollowingtwotables: createtabledept( didint, dnamevarchar(30), primarykey(did) ); createtableemp( eidint, enamevarchar(30), didint,departmentid hiredatedate, salarynumber, primarykey(eid), foreignkey(did)referencesdept(did)); 37 Exercise Declareavariabled_nameoftypedept.dname, andgiveitavalue'service',printthevariableon screen 38 CommonErrors n n Miss%betweencolumnnameandtype Misstablename 39 RowTypeVariable n n n n Tablename%ROWTYPE:assumesdatatypeof entirerow,whereeachcolumnasafieldofthistype Usevariable_name.column_nametorefertoafieldof thevariable OftenusedininsertorstoreresultsofaSQLquery Benefits? 40 RowType Examples Declare Rec1dept%rowtype; Begin n Rec1.did:=3; Rec1.dname:='service'; InsertintodeptvaluesRec1; End; 41 Exercise n Declareavariablenew_emphavingtherow typeofemp.Assignvalue'john'totheename fieldofthevariable.Printouttheenamefield ofthevariable Declare new_empemp%rowtype; Begin new_emp.ename:='jeff'; dbms_output.put_line(new_emp.ename); End; 42 CommonErrors Miss%betweentablenameandrowtype n Miss.Betweenrowtypevariablenameand columnname n Dbms_output.put_linecannottakearowtype input,soyoumustuse row_type_variable.column_name E.g.,dbms_output.put_line(new_emp.ename); n 43 AssignmentStatements(cont.) Forcompositetypes,onlyiftypesarethesame Anyprobleminthefollowingprogram? Declare Rec1emp%rowtype; Rec2dept%rowtype; Begin Rec1.eid:=6; Rec1.ename:='Bob'; Rec1.did:=1; Rec2:=Rec1; End; Notworkbecausecolumnisnotmatch. 44 ArithmeticOperators Example n n n n n n n **Exponentiation2**38 *Multiplication2*36 / Division 9/24.5 +Addition3+25 Subtraction 321 Negation 5 Negative5 Ln()NaturallogLn(10) Result 45 Exercise n Printouttheresultof2**10 46 NULLValuesinAssignment Statements n n n n Untilavalueisassignedtoavariable,the variable'svalueisNULL Performinganarithmeticoperationona NULLvaluealwaysresultsinaNULLvalue dbms_output.put_linewilloutputnothingfora nullvalue Advice:Alwaysinitializevariablevalues 47 Example n Whatwillbescreenoutput? Declare xvarchar(20); Begin dbms_output.put_line(x); x:='hello'; end; 48 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n n Basicstructure Variables Assignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 49 PL/SQLControlStructures n n Conditional:ifandcasestatements Loopandexit 50 PL/SQLSelectionStructures IF/ENDIF: IF condition THEN program statements END IF; 51 PL/SQLSelectionStructures Example: Declare Xdate; Begin x:=sysdate; ifx>date'200691'then dbms_output.put_line(x||'laterthan200691'); Else dbms_output.put_line(x||'earlierthan200691'); Endif; End; 52 PL/SQLSelectionStructures IF/ELSIF: IFcondition1THEN programstatements; ELSIFcondition2THEN alternateprogramstatements; ELSIFcondition3THEN alternateprogramstatements; ... ELSE alternateprogramstatements; ENDIF; 53 PL/SQLComparisonOperators SameasSQL =,<>,>=,<=,<,> n Logicaloperators ANDORNOT E.g.,x>10andx<20 n Comparisonwithnullvalues: Ifxisnullthen Ifxisnotnullthen Cannotuse: Ifx=nullthen(later) n 54 PL/SQLSelectionStructures Exercise:useifelsif Printout'TodayisinSeptember2006'iftodayisnolater than200691andisearlierthan2006101, Printout'todayisbeforeSept2006'iftodayisbefore2006 91 Printout'todayisafterSept.2006'iftodayisequaltoor after2006101 55 CommonErrors n n n Spelling:elsif(correct)ratherthanelseif Forgetendif Forgettogivethevariableintheconditiona value(next) 56 EvaluatingNULLConditionsin IF/THENStructures n n IfaconditionevaluatesasNULL,thenitis FALSE HowcanaconditionevaluateasNULL? n Itusesanyvariablethathasnotbeeninitialized 57 PL/SQLSelectionStructures Whatwillbetheoutput?Ifaconditionevaluatesas NULL,thenitisFALSE Declare Xinteger; Begin x:=10; ifx>0then dbms_output.put_line(x||'greaterthanzero'); Elsifx=0then dbms_output.put_line(x||'equaltozero'); Else dbms_output.put_line(x||'lessthanzero'); Endif; End; 58 PL/SQLSelectionStructures Howtocheckanullvalue? Declare Xinteger; Begin ifxisnullthen dbms_output.put_line('nullinput'); elsifx>0then dbms_output.put_line(x||'greaterthanzero'); Elsifx=0then dbms_output.put_line(x||'equaltozero'); Else dbms_output.put_line(x||'lessthanzero'); Endif; End; 59 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n n Basicstructure Variables Assignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 60 PL/SQLLoops Loop:repeatsoneormoreprogram statementsmultipletimesuntilanexit conditionisreached OftenneededwhenweprocessresultsofaSQL query 61 PL/SQLLoops Example: Declare Totalinteger; iinteger; Begin i:=1; total:=0; loop total:=total+i; i:=i+1; exitwheni>10; Endloop; dbms_output.put_line('totalis'||total); End; 4 62 PL/SQLLoops Declare Totalinteger; iinteger; Begin i:=1;initializationbeforeloop total:=0;initializationbeforeloop loop total:=total+i; i:=i+1; exitwheni>10; Endloop; dbms_output.put_line('totalis'||total); End; Initializationbeforeloop:iisaloopvariable(usedtotellwhentoendloop), totalistheresultwecompute.Bothneedtobeinitialized. i=1becauseyouwanttostartwith1 total=0becauseyouarecomputingasum 63 PL/SQLLoops Declare Totalinteger; iinteger; Begin i:=1; total:=0; loopstartofloop total:=total+i;repeatedaction i:=i+1; exitwheni>10; Endloop;endofloop dbms_output.put_line('totalis'||total);postloopaction End; Repeatedactioniswhatyouwanttodousingtheloop(e.g.,computea sum) 64 PL/SQLLoops Declare Totalinteger; iinteger; Begin i:=1; total:=0; loopstartofloop total:=total+i; i:=i+1;updateloopvariableifany exitwheni>10; Endloop;endofloop dbms_output.put_line('totalis'||total);postloopaction End; Youneedtoupdatetheloopvariable(counter)becauseotherwiseyouwill haveinfiniteloop. 65 PL/SQLLoops Declare Totalinteger; iinteger; Begin i:=1; total:=0; loopstartofloop total:=total+i; i:=i+1; exitwheni>10;checkexitcondition Endloop;endofloop dbms_output.put_line('totalis'||total);postloopaction End; Youalsoneedtocheckexitconditionbecauseotherwiseitwillbean infiniteloop.Hereyouwanttoendloopwheni>10becauseyouwantto computeasumfrom1to10 66 PL/SQLLoops Declare Totalinteger; iinteger; Begin i:=1; total:=0; loopstartofloop total:=total+i; exitwheni>=10;checkexitcondition i:=i+1; Endloop;endofloop dbms_output.put_line('totalis'||total);postloopaction End; Theexitconditionmaychangedependingonwheretotestthecondition. Thebestwaytomakeitrightisleti=boundaryvalue(10)andgothrough thelooptocheckifyouwanttoexit. 67 Exercise n Computetheproductof1,2,3,4usingaloop 68 CommonErrors n n Forgetinitializationbeforetheloop Infiniteloop n n n Forgettoupdateloopvariable Forgettoaddexitcondition Incorrectexitcondition n n Exitifvariableisoutofrange Manualcheckofboundaryvaluescanfixthis 69 PL/SQLLoops Anyprobleminthefollowingprogram? Declare Totalinteger; Iinteger; Begin I:=1; total:=0; loop total:=total+I; exitwhenI>10; Endloop; dbms_output.put_line('totalis'||total); End; 4 70 NumericFORLoop(Optional) FORcounter_variable IN[reverse]start_value..end_value LOOP programstatements ENDLOOP; n n n n n n Noneedtodeclarecounter_variable.Ifitisnotdeclared,itisonlyvalid inloop(cannotuseitbeforeorafterloop) Cannotmodifycounter_variableinsidetheloop Start_valuealwayslowerthanend_value Usereverseifyouwanttostartfromend_value Thelooprepeatedend_valuestart_value+1times Usingexitwhenstatementwhenyouwanttojumpoutofforloop 71 NumericFORLoop(Optional) Declare totalinteger:=0; begin FORiIN1..10LOOP total:=total+i; ENDLOOP; dbms_output.put_line(total); End; 72 Exercise(Optional) n Computetheproductof1,2,3,4usingforloop 73 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n n Basicstructure Variables Assignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 74 UsingSQLCommandsinPL/SQL Programs n Candirectlyuseinsert,update,delete, commit,rollback 75 UsingSQLCommandsinPL/SQL Programs n Canuseselectthroughcursors n n n n Needawaytostoreresultsofselecttolocal variables Cursorisavariablepointingtoaresultrow Aloopisoftenneededifresultscontainmultiple rows CanuseDataDefinitionstatementsthrough dynamicSQL(later) n DDLincludingcreate,drop,alter,grant,revoke 76 UsingInsert,Update,Delete n CanusethemasinSQL,i.e.,notreferringto anyvariables Begin insertintoemp values(5,'alice',1,date'200691',45000); End; 77 UsingInsert,Update,Delete n Canrefertoanyinitializedvariableswhereavalueis expected Declare Dept_idnumber; Begin dept_id:=2; updateemp Setdid=dept_id Whereeid=4; End; 78 InsertUsingRowtypeVariable declare xemp%rowtype; Begin x.eid:=5; x.ename:='alice'; x.did:=1; x.hiredate:=date'200691'; x.salary:=45000; insertintoempvaluesx; end; 79 Exercise n Insertanewdepartmentwithdid=4and dname='accounting',pleaseusearowtype variableinyourinsertstatement 80 CommonErrors n Insert:thecolumnvaluesandordersmust matchcolumntypesandcolumnorders n Fordatetype,don'tforgetdateprefix 81 UsingSelect n n Mustuseacursortorefertoresults Followingexamplewillgetanerror Begin selecteid,ename fromemp; End; 82 Cursor n n Pointertoaservermemorylocation Containsinformationabouttheresultsofa SQLcommandinaPL/SQLprogram n Calledthecommand'scontextarea Cursor Numberof rows processed active set CID 1 2 3 4 5 CALLID MIS 101 MIS 301 MIS 441 CS 155 MIS 451 Parsed command statement CNAME Intro. to Info. Systems Systems Analysis Database Management Programming in C++ Client/Server Systems CCREDIT 3 3 3 3 3 83 TypesofCursors Implicit Easiertouse ResultsmustbeEXACTLYonerow Explicit Morecomplextouse Resultscanbeonerow,multiplerows,oreven empty Cursorcannotappearinassignmentor expressions 84 ImplicitCursors SELECT column1, column2, INTO variable1, variable2, FROM tablename WHERE search_condition; Canonlybeusedifqueryreturnsoneandonlyone record Variablesmusthavebeendeclaredandhavethe sametypeasresults Forstrings,makesurethevariable'ssizeislong enoughtostoretheresults(that'swhycolumntypeis useful) 4 85 ImplicitCursorSyntax(cont.) Declare E_idnumber; E_namevarchar(50); Begin selecteid,enameintoe_id,e_name fromemp Whereeid=1; Dbms_output.put_line('e_idis:'||e_id||'e_nameis:'|| e_name); end; 86 Exercise n Useimplicitcursortoreturnthesalaryof employeewhoseidis1,printoutthesalary 87 CommonErrors n n n n SQLstatementdoesnotreturn1row Forgettodefinevariableusedtostoretheresult Thevariable'sdatatypedoesnotmatchtheresult (userowtypeorcolumntypewillavoidthisproblem) SQLstatementerror(usecorrecttablename, columnname,donotconfusewithvariables).You cantestyourSQLstatementfirst 88 ConditiononPrimaryKey Declare E_idnumber; E_namevarchar(50); Begin selecteid,enameintoe_id,e_name fromemp Whereeid=1; Dbms_output.put_line('e_idis:'||e_id||'e_nameis:'||e_name); end; n Whytheselectstatementonlyreturnsonerow? 89 NoRowsReturned Declare E_idnumber; E_namevarchar(50); Begin selecteid,enameintoe_id,e_name fromemp Whereeid=10; Dbms_output.put_line('e_idis:'||e_id||'e_nameis:'|| e_name); end; 90 NoRowsReturned Declare E_idnumber; E_namevarchar(50); Begin selecteid,enameintoe_id,e_name fromemp Whereeid=10; Dbms_output.put_line('e_idis:'||e_id||'e_nameis:'|| e_name); end; Anexception(nodatafound)willbereported,solution? 91 Exception Declare E_idnumber; E_namevarchar(50); Begin selecteid,enameintoe_id,e_name fromemp Whereeid=10; Dbms_output.put_line('e_idis:'||e_id||'e_nameis:'||e_name); Exception whenno_data_foundthen Dbms_output.put_line('norowsfound'); whentoo_many_rowsthen dbms_output.put_line('toomanyrows'); End; 92 ExceptionSyntax Exception Whenexception_namethen handleexception Whenexception_namethen handleexception whenothersthen handallotherexception n 93 ExceptionsforImplicitCursor n n No_data_found(caseinsensitive) Too_many_rows 94 Exercise n Useimplicitcursortoreturnthesalaryof employeewitheid=5.Pleasehandle exceptions 95 Aggregations(Optional) n Exceptions? Declare avg_salnumber; Begin 4; selectavg(salary)intoavg_salfromempwheredid= dbms_output.put_line(avg_sal); End; 96 Aggregations(Optional) Incaseemptyanswers,checkifresultisnull Declare n avg_salnumber; Begin selectavg(salary)intoavg_salfromempwheredid=4; ifavg_salisnotnullthen dbms_output.put_line(avg_sal); else dbms_output.put_line('Nosuchemployees'); endif; End; 97 TipsforImplicitCursor n Useitonlyfortwocases: n n n Whereconditiononprimarykey(zerooronerows) Aggregationswithoutgroupby(1row) Otherwiseuseexplicitcursor(next) 98 Roadmap n n n MotivationforPL/SQL Anonymousvs.namedPL/SQLsubprogram BasicPL/SQLfeatures: n n n n Basicstructure VariablesandAssignment Controlstructures(ifthen,loop) UsingSQLinPL/SQL n n n Insert,update,delete Implicitcursor(select) Explicitcursor(select) 99 ExplicitCursors MustbedeclaredinprogramDECLAREsection Canbeusedifqueryreturnsmultiplerecordsor norecords 100 UsinganExplicitCursor Declarethecursor Openthecursor FetchthecursorresultintoPL/SQL programvariablesusingaloop Makesurecheckexitconditioninloop (whatconditiontocheck?) Closethecursor 101 Template Declare Cursor cursor_name is SQL-statements; Variable-definitions; Begin Open cursor_name; loop FETCH cursor_name INTO variable_name(s); exit when cursor_name%notfound; -- handle results, e.g., print them out End loop; Close cursor_name; 102 FetchingExplicitCursorRecords Declare Cursorc1isSelectename,dnameFromemp,deptwheredept.did= emp.did;cursordefinition e_nameemp.ename%type;variablestoholdresults e_deptdept.dname%type;variablestoholdresults Begin Openc1;opencursor Loop Fetchc1intoe_name,e_dept;fetch Exitwhenc1%NOTFOUND;exitcheck Dbms_output.put_line('name='||e_name|| ',dept='||e_dept); ENDLOOP; Closec1;closecursor END; 103 Exercise n Useanexplicitcursortoprintoutnamesof employeesworkingatITdepartment 104 CommonErrors n Cursordefinitionerror:makesureyoutryoutthe SQLstatementbeforedefiningthecursor n n n n n n n DoNOTusevariablenamesthatarethesameastableor columnnames Forgettocheckexitcondition(neverdothis!) Forgettoopencursor Forgettofetchcursorintheloopbody Forgetusingaloop Forgettoclosecursor Wrongorderintheloop(mustbefetch,exittest, processresults) 105 Error? Declare Cursorc1isSelectename,dnameFromemp,deptwheredept.did= emp.did;cursordefinition e_nameemp.ename%type;variablestoholdresults e_deptdept.dname%type;variablestoholdresults begin openc1;opencursor loop fetchc1intoe_name,e_dept;fetch dbms_output.put_line('name='||e_name|| ',dept='||e_dept); print ENDLOOP; Closec1;closecursor END; 106 Error? Mustcheckexitcondition,otherwiseyouwillgetaninfiniteloop Declare Cursorc1isSelectename,dnameFromemp,deptwheredept.did= emp.did;cursordefinition e_nameemp.ename%type;variablestoholdresults e_deptdept.dname%type;variablestoholdresults begin openc1;opencursor loop fetchc1intoe_name,e_dept;fetch dbms_output.put_line('name='||e_name|| ',dept='||e_dept); print exitwhenc1%notfound; ENDLOOP; Closec1;closecursor END; n 107 Whatifcheckconditionafterprint? Declare Cursorc1isSelectename,dnameFromemp,deptwheredept.did= emp.did;cursordefinition e_nameemp.ename%type;variablestoholdresults e_deptdept.dname%type;variablestoholdresults begin openc1;opencursor loop fetchc1intoe_name,e_dept;fetch dbms_output.put_line('name='||e_name|| ',dept='||e_dept); print exitwhenc1%NOTFOUND;exitcheck ENDLOOP; Closec1;closecursor END; 108 Whatifcheckconditionafterprint? loop fetchc1intoe_name,e_dept;fetch dbms_output.put_line('name='||e_name|| ',dept='||e_dept); print exitwhenc1%NOTFOUND;exitcheck ENDLOOP; Errorbecauseweshouldprintonlyifexitconditionisnot satisfied Soweprintonemoretimewhentheexitconditionissatisfied n n Similarly,fetchshouldbeplacedbeforeexitbecauseonly fetchwillupdatecursorstatus(notfoundornot),andwecan notcheckcursorstatusbeforeitisupdated 109 Sticktotheorderoffetch,exit,print Declare Cursor cursor_name is SQL-statements; Variable-definitions; Begin Open cursor_name loop FETCH cursor_name INTO variable_name(s); exit when cursor_name%notfound; -- handle results, e.g., print them out End loop; Close cursor_name; 110 UseRowtypeVariable Declare Cursor cursor_name is SQL-statements; Variable-name cursor_name%rowtype; Begin Open cursor_name loop FETCH cursor_name INTO variable_name; exit when cursor_name%notfound; -- handle results, e.g., print them out End loop; Close cursor_name; n The row type variable will have columns in the select clause of SQL n You can use variable-name.column-name after fetch 111 UseRowtypeVariable Declare Cursorc1isSelectename,dnameFromemp,deptwheredept.did= emp.did;cursordefinition rc1%rowtype;variablehasthesametypeasarowreturnedbythecursor begin openc1;opencursor loop fetchc1intor;fetch exitwhenc1%NOTFOUND;exitcheck dbms_output.put_line('name='||r.ename|| ',dept='||r.dname); ENDLOOP; Closec1;closecursor END; 112 TipsforEfficientPL/SQL n n Trytominimizetheamountofprocessing doneinPL/SQL,pushmostprocessingto SQL DonotissuemanySQLstatements (overheadofparsingsql,allocatememoryfor cursor,passingresultsback,etc.) 113 PL/SQLjustprintoutresults Declare Cursorc1isSelectename,dnameFromemp,deptwheredept.did= emp.did;cursordefinition e_nameemp.ename%type;variablestoholdresults e_deptdept.dname%type;variablestoholdresults begin openc1;opencursor loop fetchc1intoe_name,e_dept;fetch exitwhenc1%NOTFOUND;exitcheck dbms_output.put_line('name='||e_name|| ',dept='||e_dept); print ENDLOOP; Closec1;closecursor END; 114 InefficientProgram Declare Cursorc1isSelectename,didFromemp; cursorc2isselectdname,didfromdept; e_nameemp.ename%type;variablestoholdresults did1emp.did%type; did2dept.did%type; e_deptdept.dname%type;variablestoholdresults begin openc1;opencursor loop fetchc1intoe_name,did1;fetch exitwhenc1%NOTFOUND;exitcheck openc2; loop fetchc2intoe_dept,did2;fetch exitwhenc2%NOTFOUND;exitcheck ifdid1=did2then dbms_output.put_line('name='||e_name|| ',dept='||e_dept); endif; ENDLOOP; closec2; Endloop; 115 Closec1;closecursor InefficientProgram n n Theaboveexampletriestodothejoinin PL/SQL Reallyinefficientbecause n n n Cursor2isexecutedonceforeachrowreturnedby cursor1(manysqlstatementsexecuted) Oraclehasmuchbetterwaystocomputeajoin (usingindex,hashtable,etc.) Don'texpectnestedloopsinvolvingcursors (youcanalwaysdoajoin) 116 Cursorwithinputparameter(Optional) Whendeclarecursor cursorname(inputparamenterparametertype) isSQLstatement Whenopencursor Opencursorname(inputparamenter) n TheSQLstatementcanusetheinput parameter 117 Cursorwithinputparameter(Optional) highestsalaryemp Declare e_nameemp.ename%type; msalemp.salary%type; cursorc1(msalnumber)isselectenamefromempwheresalary= msal; begin selectmax(salary)intomsalfromemp; if(msalisnotnull)then openc1(msal); loop fetchc1intoe_name; exitwhenc1%NOTFOUND; dbms_output.put_line('name='||e_name); ENDLOOP; Closec1; endif; END; 118 ForLoop(Optional) CursorFORLoopapproach: Declare cursorcursor_nameisselectstatement begin FORrowtypevariableincursor_nameLOOP processingstatements; ENDLOOP; End; n Donotopen/close/fetchcursor(getopened/closed/fetched automatically) n Noneedtodeclarethevariables.Arowtypevariableis createdautomatically n Youcanstilladdexitconditiontoendloopearlier n 119 ForLoop(Optional) CursorFORLoopapproach: Declare Cursorc1isSelectename,dnameFromemp,deptwhereemp.did =dept.did; begin n foriteminc1 loop dbms_output.put_line('name='||item.ename||',dept='|| item.dname); ENDLOOP; END; 120 ExplicitCursorAttributes Attribute Return Value %NOTFOUND TRUE when no rows left to fetch; FALSE when rows left to fetch TRUE when rows left to fetch; FALSE when no rows left to fetch Number of rows a cursor has fetched so far TRUE if cursor is open and FALSE is cursor is closed %FOUND %ROWCOUNT %ISOPEN Note that notfound, found, and rowcount are only valid after the cursor is open and result has been fetched at least once These variables may change values after each fetch 121 UseRowcounttolimitresultsize Returntwoemployeeswithhighestsalary Declare Cursorc1isSelectenamefromemporderbysalarydesc; e_nameemp.ename%type; begin openc1; loop fetchc1intoe_name; exitwhenc1%notfoundorc1%rowcount>2; dbms_output.put_line('name='||e_name); ENDLOOP; Closec1; END; 122 CommonError Returntwoemployeeswithhighestsalary Declare Cursorc1isSelectenamefromemporderbysalarydesc; e_nameemp.ename%type; begin openc1; loop fetchc1intoe_name; exitwhenc1%rowcount>2; dbms_output.put_line('name='||e_name); ENDLOOP; Closec1; END; Whatswrongwiththeexitcheck? 123
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

UMBC - IS - 620
AdvancedPL/SQLProgrammingIS620AdvancedDatabaseProjects1RoadmapnnnnnnProceduresHowtodebugPL/SQLprogramFunctionsDynamicSQLHowtoAutomaticallyGenerateValuesDuringInsertVArrayDataType2NamedProgramTypesnnnnProceduresFunctions(procedur
UMBC - IS - 620
Exam1nnnnWhen:3/34:305:45Where:classroomWhattobring:twopagedoublesidedcheatsheet,pencilsWhatNOTtouse:anyelectronicdevicesincludingdesktop,laptop,cellphone,PDA1Exam1nnnWhattocover:SQL,PL/SQLpart1Materials:slides,inclassdiscussions,homewor
UMBC - IS - 620
Exam2nnnnWhen:4/144:305:45Where:classroomWhattobring:twopagedoublesidedcheatsheet,pencilsWhatNOTtobring:anyelectronicdevicesincludinglaptop,cellphone,PDAExam2nnnWhattocover:Procedures&amp;functions,Trigger&amp;authorization,XMLMaterials:slides,ex
UMBC - IS - 620
FinalExamnnnnWhen:5/12,4:30pm6:00pmWhere:CourseclassroomWhattobring:twopagedoublesidedcheatsheet,pencilsWhatNOTtobring:anyelectronicdevicesincludinglaptop,cellphone,PDAFinalExamnnWhattocover:Storage,indexes,queryoptimization,transactions,co
UMBC - IS - 620
AdvancedDatabaseProjectsIS620ZhiyuanChenITE423zhchen@umbc.edu1OutlinennnnnnContactinformationPrerequisiteCoverageResourcesGradingSurvivalguide2CourseAdministrationnnnLocation:ITE467Time:Thursday4:307Officehours:ITE423Tuesday&amp;Wed
UMBC - IS - 620
A Short Guide of Loop andRecursive ProgrammingIS 620Example of Hw 6Find someones manager and higher levelmanagers (i.e., managers managers).EricBobAliceJeffUsing Recursive ProgrammingTo solve a complex problem, we can firstsolve one step of t
UMBC - IS - 620
IS 620 Assignment 1Due 2/3Problem 1. Consider the employee database with the following list of tables. Pleasecreate these tables with appropriate primary keys &amp; foreign keys. You can assumeboth employee_name and company_name are unique. [50 points]Th
UMBC - IS - 620
IS 620 Assignment 2Due 2/10.Suppose you have created tables in assignment 1 listed below. Please write SQLstatements for the following problems.Tables:Employee(employee_name, street, city)Works(employee_name, company_name, salary)Company(company_na
UMBC - IS - 620
IS 620 Assignment 3Due 2/17Suppose you have created tables in assignment 1 as followsTables:Employee(employee_name, street, city)Works(employee_name, company_name, salary)Company(company_name, city)Manages(employee_name, manager_name)Please write
UMBC - IS - 620
IS 620 Assignment 4Due 2/24Suppose you have created tables in assignment 1 (listed in textbook page 116 Figure3.12, also listed below).Tables:Employee(employee_name, street, city)Works(employee_name, company_name, salary)Company(company_name, city)
UMBC - IS - 620
IS 620 Assignment 5Due 3/3Suppose you have created tables in assignment 1:Employee(employee_name, street, city)Works(employee_name, company_name, salary)Company(company_name, city)Manages(employee_name, manager_name)Problem 1. Use implicit cursor t
UMBC - IS - 620
IS 620 Assignment 6Due 3/17Suppose you have created tables in assignment 1 (listed in textbook page 116 Figure3.12, and also listed below).Employee(employee_name, street, city)Works(employee_name, company_name, salary)Company(company_name, city)Man
UMBC - IS - 620
IS 620 Assignment 7Due 4/7Suppose you have created tables in assignment 1 (listed in textbook page 116 Figure3.12, and also listed below).Employee(employee_name, street, city)Works(employee_name, company_name, salary)Company(company_name, city)Mana
NYU - COMM - 1750
DEFINITION OF PUBLICRELATIONSDEFINITION OF PUBLICRELATIONS MANAGEMENT OFCOMMUNICATIONDEFINITION OF PUBLICRELATIONS MANAGEMENT OFCOMMUNICATION INVOLVING PUBLICSDEFINITION OF PUBLICRELATIONS MANAGEMENT OFCOMMUNICATION INVOLVING PUBLICS WITH
NYU - COMM - 1750
PublicRelationsJanuary 24, 2012Public Relation?:Narrative to the publicWay perceived by the publicDefinition of PR:Management of communicationInvolving publicsWith objectives in mindLarger organizational market in mindExamples of PR:Carnival Cr
NYU - ECON - UA-2
February 22nd, 2012Today and next two lectures:CostI. PerspectiveFirms goal: maximize total profitCan be major corporations, shareholders with stocksTotal profit: ( TT [pi])Total profit= total revenue total costII. Basic Principles of Cost1. Cost
NYU - COMM - comm
MCC-UE3 History of Media &amp; Communication: Spring 2011/ Recitation Syllabus Section 009: Thursdays, 3:304:45pm; 25 W 4th, Room C-4TA: Xiaochang LiEmail: xiaochang@nyu.edu* I will generally respond to emails within 24 hours on weekdays (usually not afte
NYU - COMM - comm
Recitation21:47Recitation #5 :February 22nd, 2012The Information - GleickShowProloguedetai-In 1948 two important developments came about. The first was electronic, the transistor. It amplifies andswitches electronic signals. The transistor sparked
NYU - COMM - comm
Reciation #4: February 16, 2012Newspapers and the Public Sphere by John Nerone Nerone contrasts the culture of books and newspapers. Books captured a timelessness,were a greater representation of the authors persona and was more personal because theyr
NYU - COMM - comm
Recitation #3: February 9, 2012Readings: Johns Ch. 1 &amp; 2; JoAnne Yates, Communication Technology and the Growthof Internal Communication, Control Through Communication; Tom Mullaney, TheChinese Typewriter,Piracy: The Intellectual Property Wars from Gu
NYU - COMM - comm
History Media:How Users &amp; Non-Users Matter:What to look in a reading:what was good about this argument?Couple summaries with problemsMust criticize the textExamples [for your papers]Skeptical about modernity [his perspective]Actor network theory:
Maryland - ENG - Eng101
Kim 1Elise KimENGL 10112/26/10FritzFinal Paper (Rough draft)cfw_Intro cfw_Thesis Although our demands for dairy and meat are satisfied, theprotection of the environment is crucial, and therefore there is a need for strongregulations of disposing a
Maryland - ENG - Eng101
Elise KimENGL 101Fritz12/2/10Self EvaluationI have always been getting Bs on my papers throughout my life, and have labeled myselfas a B- writer, until my first semester of college. My development as a writer at the Universityof Maryland has been i
Maryland - ENG - Eng101
Elise KimENGL10111/30/10FritzFinal Research Paper: Rhetorical SituationExigence: I am writing this paper because I think it is important for the audience to knowthe holistic view of animal wastes. There are many problems that derive from theexcreme
Maryland - ENG - Eng101
Elise KimENGL 101Fritz11/18/10Improvements in the Management of Animal WasteOver the past century, the animal industry has been growing tremendously because ofthe great demands for meat and dairy products. The push for mass production in the livesto
Maryland - ENG - Eng101
Elise KimENGL10111/9/10FritzConsidering Another Side: Rhetorical SituationExigence: I am writing this paper because I think it is important for the audience to get afeel for what farmers have to do daily in order to keep the farm going. I want them
Maryland - ENG - Eng101
Elise KimENGL10110/14/10FritzRhetorical SituationExigence: I am writing this paper because I have a passion for both animals and theenvironment. I want to know more about animal care and sustainability.Audience: The audience for this paper will be
Maryland - ENG - Eng101
Elise KimENGL 101Fritz11/4/10Topic MemoAfter writing the Evidence and Experience paper, I noticed that all the articles Iused addressed the issues of animal waste affecting only the environment. I thought itwas important to include what the farmers
Maryland - ENG - Eng101
xpSource/CategorySource 1: Waterquality (Cooper)Conjecture/DefinitionAnimal waste is a majorpollutant of water.Source 2:IndustrializedAnimal ProductionA MajorSource of Nutrientand MicrobialPollution to AquaticEcosystems(Mallin and Cahoon)How
Maryland - ENG - Eng101
Elise KimENGL 10110/26/10FritzAnimal Wastes and its ConsequencesThe high demand for meat, milk, and eggs in the United States has increased overthe past century causing the livestock industry to evolve, forcing the production of animalsto become mo
Maryland - ENG - Eng101
Works CitedCooper, M. H. (2000, November 24). Water quality. CQ Researcher, 10, 953- 976.RetrievedOctober11,2010,fromCQResearcherOnline,http:/library.cqpress.com/cqresearcher/cqresrre2000112400.Osterberg, David, and David Wallinga. &quot;Addressing
Maryland - ENG - Eng101
Elise KimENGL10110/14/10FritzRhetorical SituationExigence: I am writing this paper because I have a passion for both animals and theenvironment. I want to know more about animal care and sustainability.Audience: The audience for this paper will be
Maryland - ENG - Eng101
Elise KimENGL 101Fritz10/7/10Topic MemoGrowing up as an animal and nature lover, I always wondered where the animalwastes went to when I saw the feces and urine go down the drain in the corner of theanimals stalls at a nearby farm. It is important
Maryland - ENG - Eng101
1Elise KimENGL 101FritzSeptember 23, 2010The Moral Obstacle of the 21st CenturyIn The Girl Effect, Nicholas D. Kristof and Sheryl WuDunn assert that theinferiority of women is present everywhere to recruit people to join their movement toimprove t
Maryland - ENG - Eng101
1Elise KimENGL 101FritzSeptember 15, 2010Quality over QuantityIn his acceptance speech for the Lifetime Achievement Award Ceremony from theNational Council for Science and the Environment, Herman Daly emphasizes how the economyshould develop quali
Maryland - ENG - WMST250
Kim 1Elise Kim5/16/11WMST250 (Lara Torsky)Final PaperOn the first day of class, we were asked to write down what we thought the definition offeminism was. I wrote: the celebration of womens social differences, such as art, culture,gender, race and
Maryland - ENG - WMST250
Throughout history, women have been obsessed with their physical looks because ofwhat the society expected and favored in them. Even in ancient times, women went to theextremes to achieve perfection. For example, in 3000 BC, because the pale look was fa
Maryland - ENG - WMST250
Elise KimI went to the 11:30- 1:00 panel that was called, Sexuality, Desire, Identity: Terrains ofSexual Knowledge, where four women, and one man, Matt Richardson, spoke. Judith Gardiner,an English and Womens Studies professor at the University of Illi
Maryland - ENG - WMST250
Kim 1Essay #1Elise KimWMST 250: Midterm essayLara Torsky03/29/11Womens CommunicationCommunication is essential to all living things in order to make things run smoothly. Thiscan be portrayed through something as small as an insect, such as a honey
Maryland - UNIV - Univ 100
Elise KimUNIV 10011/29/2010JournalAt the beginning of this semester, I was afraid of not being able to make friendsbecause of my shy nature. However, it didnt take long to build friendships because ofone floor-mate I met during the first week of col
Maryland - UNIV - Univ 100
Elise Kim10/11/10UNIV100Journal #3Before I came to the University of Maryland I thought that college l was going tobe hard because its a new and different environment. However, my first half of thissemester was a good way for me to adjust at the Uni
Maryland - UNIV - Univ 100
UNIV100Fall,2010Sections1503TheStudentintheUniversitySurvivingatUM&amp;theCollegeofAgriculture&amp;NaturalResourcesCourseSyllabusInstructor:TAMr. Tim Lapanne(Section 1503)0104 Symons Hall(301) 405-5308Courtney Shaycshay@mail.umd.eduOurClassroom:321
Maryland - UNIV - Univ 100
Elise KimUNIV 1009/27/2010A)I made many friends on Friday during the All Niter. They were all friends of oneof my friends from my floor and they are in Navigators, a Christian club. We playedgames together in the basement of Denton. It was very fun!
Maryland - UNIV - Univ 100
Elise KimUNIV 1009/27/2010A)I made many friends on Friday during the All Niter. They were all friends of oneof my friends from my floor and they are in Navigators, a Christian club. We playedgames together in the basement of Denton. It was very fun!
Maryland - UNIV - Univ 100
Elise KimUNIV 100Lapanne9/27/10Meetcha TeachaIt was very hard for me to pick a professor I wanted to interview, but Ichose Dr. Updike, my Animal Science 101 and Animal Science 103 professorbecause he is the teacher that Im majoring in, Animal Scien
Maryland - UNIV - Univ 100
Elise KimUNIV 1009/6/2010A) This week, I learned how to navigate through the campus by asking people fordirections. They were all surprisingly nice and I was grateful that they didnt giveme the wrong directions. Now that I can go to different places
Regis - ACCOUNTING - 401
ch01Student: _1.Taxes influence many types of business decisions but generally do not influence personal decisions.True False2.Taxes influence business decisions such as where a business should locate or how a business should bestructured.True Fal
Regis - ACCOUNTING - 401
ch02Student: _1.Corporations are required to file a tax return annually regardless of their taxable income.True False2.The tax return filing requirements for individual taxpayers only depend on the taxpayer's filing status.True False3.If a taxpay
Regis - ACCOUNTING - 401
ch03Student: _1.The goal of tax planning is tax minimization.True False2.Nontax factors do not play an important role in tax planning.True False3.Virtually every transaction involves the taxpayer and two other parties that have an interest in the
Regis - ACCOUNTING - 401
ch04Student: _1.Relative to for AGI deductions, from AGI deductions tend to relate to items that are more personal innature.True False2.Taxpayers need not include an income item in gross income unless there is a specific tax provisionrequiring the
Regis - ACCOUNTING - 401
ch05Student: _1.Gross income includes all income realized during the year.True False2.Excluded income will never be subject to the federal income tax.True False3.The all-inclusive definition of income means that gross income is defined very broad
Regis - ACCOUNTING - 401
ch06Student: _1.The profit motive distinguishes &quot;business&quot; activities from &quot;personal&quot; activities.True False2.All business expense deductions are claimed above the line.True False3.All investment expenses are itemized deductions.True False4.Ren
Regis - ACCOUNTING - 401
ch07Student: _1.Both the width (or range) of the tax brackets (the amount of income taxed at a particular rate) in the taxrate schedules and the range of the tax rates in the tax rate schedules (the difference between the lowesttax rate and the highe
Regis - ACCOUNTING - 401
ch08Student: _1.The Internal Revenue Code authorizes deductions for trade or business activities if the expenditureis &quot;ordinary and necessary&quot;.True False2.Business activities are distinguished from other activities in that business activities are m
Regis - ACCOUNTING - 401
ch09Student: _1.Like financial accounting, most business property must be capitalized for tax purposes.True False2.Tax cost recovery methods include depreciation, amortization, and depletion.True False3.If a business mistakenly claims too little
Regis - ACCOUNTING - 401
ch10Student: _1.The amount realized is the sale proceeds less the adjusted basis.True False2.Generally, the amount realized is everything of value received in a sale less selling expenses.True False3.The adjusted basis is the cost basis less cost
Regis - ACCOUNTING - 401
ch11Student: _1.Generally, interest income is taxed at preferential capital gains rates and dividend income is taxed atordinary rates.True False2.Interest earned on U.S. savings bonds is interest received at sale or maturity but must be taxedannua
Regis - ACCOUNTING - 401
ch12Student: _1.Current compensation is usually comprised of salary, wages, and bonuses.True False2.Employees complete a Form W-2 to specify their income tax withholding.True False3.Employers computing taxable income receive a deduction for salar
Regis - ACCOUNTING - 401
ch13Student: _1.Qualified retirement plans include defined benefit plans but not defined contribution plans.True False2.Defined benefit plans specify the amount of benefit an employee will receive on retirement while definedcontribution plans speci
Regis - ACCOUNTING - 401
ch14Student: _1.In general terms, the tax laws favor taxpayers who own their principal residence relative to taxpayers whorent it.True False2.Renting a residence may have nontax advantages over owning a home.True False3.A personal residence is n
Regis - ACCOUNTING - 401
ch15Student: _1.Corporations are legally formed by filing articles of organization with the state in which the corporationwill be created.True False2.General partnerships are legally formed by filing a partnership agreement with the state in which