0% found this document useful (0 votes)
17 views13 pages

Chapter 6 IMP

PS/SQL XII SCIENCE

Uploaded by

Sulbha Gath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

Chapter 6 IMP

PS/SQL XII SCIENCE

Uploaded by

Sulbha Gath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
aw 3. One can create a PL/SQL unit stich as packages, trikes, and types, which are ator ‘reuse By applications 4 PL/S01. provides a feature to handle We exception which ou, PL/SQL block known as exception handling block. pS ‘5. Applications written in PL/SQL are portable to or OF operating systera where Oracle Is operational 6, PL/SQL Offers extensive error checking, ‘Advantage of Using PL/SQL. 1. Beer performance, 9% SOI. is exceuted tn bulk rath statement 2. High Productivity 3. Tight integration with SQL 4. Pull Portabiiy 5, Tight Security 6. Support Object Oriented Programniing concepts Disadvantages of SQL : © SQL docsn't provide the programmers with a technique of condition ‘checking. looping and branching '* SOL statements are passed to Oracle engine one at a time which Increases trafic and decreases speed. rat ann PUIEEardany er than a singe © SOL has no faclty of error checking during manipulation of data. PL/SQL Basics ike other programming languages, PL/SQL. has a character set, | ‘Feserved words, punctuation, datatypes, and fixed syntax rules, Character Se(s and Lexleal Units PL/SQL programs are written as 62 lines of text using a specific set of / my [Compas] 9 Vopr ee a ha a $ sumerats 0. 9 S symbols 0) +-* foes sac Tabs, *PACES, and carriage returns PL/SQL keywords are not case Janguages. resulting ina structural ‘90L- The baste unit in PL/SQL isa block A LISI. programs are made up of blocks. which can be nested within each caer ecaRe declaration aatemenis: Beom cela sstemenis EXCEPTIONS ‘xcepton handing statements es (© Declare seetion starts with DECLARE keyword im wich variables constants, records as cursors can be declared whch stores data temporary. It basicaly consists definition of PL/SQL identiers. ‘This part of the code is optional. Execution section starts with BEGIN and ends with END keyword. ‘This Js a mandatory section and here the program loge s written to perform any task lke loops and consitonal statements It supports all DML commands, DDL commands and SQL‘PLUS builtin functions as wel. (Comparer tence XD] per isa ot + enn re tr th RCETTON eT eg fee ion in coapeommmtepeaadainemnt) Jostein Ck cn tine error occurs. Any exceptions canbe handled in this saci” ace i te. Sonata, ables: Like ee ‘Geemrrepenee jpame and data type as well, ‘They should have a vad ‘syntax for declaration of variables ; ; ‘sarale-tamedatatype INOT MULL = value Example to show howto dete vata Sob Set semenoxnrer og nn SO SQ1> DECLARE ‘art INTEGER: ward REAL: vars varar2;20 pean ll: END: / Output PL/SQL procedure snccossTully completo | xplanation | © SET SERVEROUTPUT ON : It is used to display the buffer used by the dbs onpat. ‘ ‘© var INTEGER : isthe declaration of variable, named vari which ib of integer typ. There are many other data types that ean be sed tke float, int. rea, smallint, Jong et. I also supports variables used sn SQL as well like NUMBERIprec, scale), varchar, varchar? sequence ofeecitate statements. ED Ir ‘Write a program in PL/SQL to check the given valve iz than 50 by using IF-THEN Statement. baer & NUMBER -00, BEGIN doms_output.put tine Program started Ia > 60) THEN Alms. output putea ts greater than 90% ddbms_ output. put linet Program completed) END: L Output: 4s greater than 50 7.2Using the IF-THEN-FLSE Statement Use the IF-THEN-ELSP format when you want to choose between ‘99 mutually exclusive actions. The forsaat ofthis either/or version of the I statement te ae follows The condition is a Boolean variable, cons v tant, or expression, ‘Meondiionevaluates to TRUE, the executable statements found after the @M) [Computer Science-Xt] = L eywordand before the ELSe es rae of executable statements ane ea aN smtaed wth ios noe Sng _ggaensrn wil usenet ene ane Se a co nos 3 te ee eywrord wate sega a Se rls tan 50 y ang INE ELSE Stroman, Deciane NUMBER = —— ea fea etna tra 50) lg St ett a nse ect pt nae i i or i ‘tens SUL em St: = i poe Taner | o.7-2tsing te I-THEN-BISI Satoment ‘This tas fora ofthe IF statement somes ts handy wien eat has any aller: sk aie siete Te TP-ELSIF formation prorides way to bande mA conditions within a single IF statement. Tn gest Jon ‘with mutually exclusive alternatives e., only one conven ean (23s) [(Conpuer Seence Xi > for any exeention of the 1 statement). The general tormat top ariaton oF ‘syntax sReondiion 1 "THEN statements ELSIF condone HEN ELSE ise. statements} END IF: Bach ELSIF clause must have a THEN after its condition, Onty the ELSE keyword doesnot nee the THEN keyword. The ELSE clause tye IFELSIF ts the "otherwise" of the statement. If none of the conditions evaluate fo TRUE, the statements inthe ELSE clause are exccuted, be the ELSE clause 6 optional. You can code an IF-ELSIF that has only tp and ELSIF clauses In such a case. tf none of the conditions are TRUE, np statements inside the IF block are executed. ‘The conditions in the IF-ELSIF are always evaluated in the order of Arst condition to last condition, If two conditions evaluate to TRUE, the Statements forthe frst such condition are executed. Wite a program in PL/SQL to deplay value of variable by using IP-THEN-BLSIF Statement. DECLARE 4 number(3)=60: BEGIN IF ( 2-10) THEN sdhnas_outputput_line(Valuie of is 10): BLSIF ( a=20) THEN cdbms_output.put_tine(Value of a ts 20}; ELSIF ( a=80) THEN LOOP: - 3 tusng FOR loop statement ‘cexecution block: ends END LOOP: ‘¢ In the above syntax, Keyword WHILE? mars b ‘and ‘END LOOP’ marks the end of the 1oop- «The execution block contains all the code that needs tobe ex Ce “¢ The execution part can contain any exccution statemcat Example : Program in PL/SQL code to print number fom using WHILE loop statement. fos initializing it with value © Code tine 4: Printing the statement “Program started” © Code line 8: Keyword ‘WHILE’ marks the beginning of the loop, and {also checks whether the value of ‘as greater than 5 “© Code tine 7: Prints the value of ‘a © Code tine 8: Increments the value of a’ by +1, © Onde line 2: Declaring the variable ‘a’ as ‘NUMBER’ data type and © Code line 9: Keyword “END LOOP" marks the end of execution Dlock. © The code from Une 7 and tine 8 wi il continue to execute till reaches the value 6, as the condition will return TRUE, and the ‘control will EXIT from the loop. Code ine 10: Printing the statement “Program completed” (2 Rampart] Te stored programs, which are itomatically executed or fred when some events sore ‘Triggers are, in fact. written to be executed in response to any of the following events : 2 A dalabase manipulation (DML) statement (DELETE, INSERT, or uppars} 4 A database definition (DDL) statement (CREATES, ALTER. or DROP). 2A. database operation STARTUP, or SHUTDOWN) ‘Triggers could be defined on the table, view, schema, or database ‘with which the event ie associated, (SERVERERROR, LOGON. LOGOFF, Benefits of Triggers ‘Triggers can be written for the following, purposes = 2 Generating some derived column values automaticaly 3. Enforcing referential integrity © Byent logging and storing information on tible access 2 Auditing © Synchronous replication of tables ‘3 Imposing security authorizations Preventing invalid transactions, Different types of triggers in PL/SQL PL/SQL has four types of triggers which are given Delo, (Computer (243) an ‘Row lve! Triggers and Statement lvel Triggers: 4 sn tee teer Io fired ence on Behalf of the eigerig teeat rogaros of the number of rows in the tie Wat the st atsement afc, A tow tiger Beex 0008 fr eats rg OH by te elgering cre a 2. BEFORE and AFTER Triggers : BEFORE tigsers nun Action before the trawering statement ie run. Berone ee ‘cute before the trigering DML slatement INSERT, Une DELETE) ctecute. AFTER triggers run the tigger action ance feigerng statement Is run. “AFTER trigger exceute ana ‘efering DML tater ONSENT, UPOATE, DELETE) cae 8. INSTEAD OF riggers : INSTEAD OF trssers decenbe Perr inser, upate i delete operations tant are too complex to support these operations naively. et OF triggers alow sppeatons wat a raw a he sole meee forall SQL operations (insert, delete, update and selec) Triggers on System Events and 8.10 Cursor 4. snpuett Cursors ae 2}. sseplet Cursors jo tompliclt Cursors : Impiet cursors awe PL/SQL. whenever an SQL statement i sxe ee not control the imple curse fzscuted. Proganimers ie, 4 the mormaton tk fPDATE and DELETES would be alerted Different attributes of inp cursor are SSFOUND, ISOPEN, SSNOTFOUND, and 9ROWCOUIT Toe OCU sa MO Eaeaiiis! Description S6FOUND Returns TRUE if an INSERT, UPDATE, or DELETE) Statement affected one or moce rows or a SELECT| INTO statement returned one or more rows. Otherwise, st returns FALSE, the logical eppesite of MFOUND. Ik returns TROP Wan INSERT, UPDATE, or DELETE statement affected 10 sows, of @ SELECT INTO statement returned no rows Otherwise, it returns FALSE. “eNOTROUND ‘Aways returns FALSE for implicit Canons, because Oracle closes the SQL cursor automaticaly. afer exeenting te associated SQL statement WROWCOUNT] Returns the number of rows affected by an INSERT, UPDATE, of DELETE. statement, or returned by a! SELECT INTO statement. Explicit Cursors ‘The Explicit cursors are defined by the progsammers to gain more control over the context area. These cursors should be defined i the eclaration section of the PL/SQL block. Tt is ereated on @ SELECT statement which returns more than one row. SAISOPEN (248), [Comper Saence-xn) ‘Syntax of plot cursor (CURSOR curmcr-narne IS select statement ‘steps You must folew these steps while working with an explicit aoe, 41. Declare the cursor : Il i used to inttiaize ia the ‘nddefnes the cursor with a name and the associated 2. Open the cursor : It is used to alloeate memory for thee ake 1 easy fo fetch the rows returned by the SQL state memory setecr 0 an "ens it, 9. Reteh the cursor : 11s used torerieve data by access one time ‘These are now cated as active sets. Fetching data from the cursor ig a reeord-evel actinty that means we can access the data tye record by-reeord 4. Close the cursor : ts use to release the allocated memory Once all the record ts fetched, we need to close the cursor #0 thatthe ‘memory allocated to this content area will be released, 6.11 Trigger Va, Cursor TRIGGER ‘Telagers are named PL SQL blocks Cursors are temporary work Cursorsare not Independently in database. We can create cursor bo ‘mplictly and expitetiy, (Cursors can take parameters Cursors are used to proc the result of query. [Computer Soience-Xi] ‘riggers are stored tn database ‘Triggers can be invoked automaticaly. ‘Triggers cannot take parameters. Trigigers are used to enforce data in dignity rules, (246) SUMMARY 4g PL/SQL stands. for Procedurt ee anguage/Strutired Query PL/SOL Is @ superset of QL. 4» PL/SQL 15 a Block Strucre language that enabies a combine the power of SQL with Procedural stale : spnlications writen tn PL/SQL are parable to any compuier ‘hardware and operating system where orace is opertional ‘PL/SQL divided Into loge back. # PL/SQL Block Struchire used four sections: Dedare Bag, Exeeptionand End, (© The Declare Section start with Declare Keyword in which mesory varlable initiizes. Ee [Rann Nees ee So pi mranees a a - ante ieee oe cor» tl on me ee ee eae — (2am) (CompaerSeenee XID) ——, ‘+ After Trigger executes the trigger action after the tr SC stam PL/SQL code to find the an 2 Mement | gtte P find the area of fo Nia aa lal stn cat ren ol @ The arca allocated for processing @ SQL statement 1s known, 4, eee soot do ses ‘© Cursors are of two (pes: Impliet and expt cursor —— ae 4 Internal processing of Oracle engine statements is known asim aout ne he te of ct ae user nite cn The Expl cursors are defined by the programmers {0 gin more bases control over the context area, The area of arce is 28.26, PL/SQL Code to find area of a rect ‘TRUE/PALSE Sol: ‘+ A.Cursor is handler or pointer tothe context area, o Dectane Unont Noon 6.2): (A Trigger fs handler oF pointer to the context area, *) REA NUMBER 1 2) Two kinds of cursor used in oracle are impliet and explitt AEA pene lie cursor a exon 3 © Avariabe is a name associate with value. ™ AREA eee DBMS OUTPUT FUT LIE AREA: ‘¢ PL/SQL stands for Procedural Language/Structure END Query Language. Output : 90 ci ode to find area of a triangle. '¢ PL/SQL ts not a Procedural Language. pe © PL/SQL is superset of SQL. © Cursor can take parameters. “© Cursor cannot take parameters, —— wm 6.25 ip Nonen 6.2): Pe SUMBER 16,1: Beer cere weit Taree nana Sos OUTeUT HUT LINE area ‘© Trigger cannot take parameters, ¢ Exror handling in PL/SQL ts called Exception, © PI/SQL supports error handling routine, fl a33asaaag END @ SQL does not has procedural capabilities. ae oe (248) [Computer Science-Xi] (249) (Comput Scene ND) — ns Write a PL/SQL program to print the series from 1 to 50. Sol: BEGIN FORNUMIN 1..50 E “9, Ee DBMS_OUTPUT.PUT_LINE (NUM | |‘ ’); ENDLOOP; e DBMS_OUTPUT.PUT_LINE (*’); END; 2 Write aPL/SQL program toprint the following series from 1,4,7,10...49, Sol: DECLARE TNUMBER (2); BEGIN i DBMS_OUTPUT.ENABLE WHILE (1<=40) LOOP DMBS_OUTPUT.PUT (I | | "); I:=1+3; ENDLOOP: DBMS OUTPUT.PUT_LINE('); END: EXERCISE Q1. What is PL/SQL ? Q2. What are advantages and disadvantages of PL/SQL ? 93. What is difference between the SQL and PL/: SQL. 94. Explain the PL/SQL blockstructure. 95. What is variable? Explain it. Q6. What do you mean by control structure ? Explain it. Q7. What do you mean by IF Statement? Explain its types with example. 98. What do you mean by loop statements/ Iterative control ? 99. Explain the FOR Loop and While Loop with an example. 910. What do you mean by Trigger?Write its advantages. 911. Explain the types of Trigger, Q12. What do you mean by cursor? What are different types of cursor? Q13. Define the Implicit cursor and Explicit Cursor, gl4. i 'd Cursor, ‘or attributes : 3) %ISOPEN 4) %ROWCOUNT 230

You might also like