Lab on Plsql

download Lab on Plsql

of 7

Transcript of Lab on Plsql

  • 8/10/2019 Lab on Plsql

    1/7

    BIRLA INSTITUTE OF TECHNOLOGY & SCIENCE, PILANI (RAJASTHAN) 333031II Semeste !00"#0$

    CS C3%! 't''se Sstems

    Lab# PL*S+L B's-s

    SQL enables us to create, organize, retrieve and maintain data stored in database it does not provide the

    features which a typical programming language offers, such as control-of-flow construct ( sequence, selectionand iteration construct ), or the facility to declare and use variables

    Overview of PL/SQLPL/!L is a bloc"-structured language# $hat is, the basic units (procedures, functions, and anonymousbloc"s) that ma"e up a PL/!L program are logical bloc"s, which can contain any number of nested sub-bloc"s# $ypically, each logical bloc" corresponds to a problem or sub problem to be solved# PL/!L is notcase-sensitive, so lower-case letters are equivalent to corresponding upper-case letters e%cept within stringand character literals#

    PL/!L provides additional capabilities that !L lac"s&

    ecure code through encryption and by storing code on a server instead of a client computer#

    'andle e%ceptions that arise due to data entry errors or programming errors#

    Process record with iterative loop code that manipulates records one at a time#

    or" with variables, records, arrays, obects, and other common programming language constructs#

    $hese are the advantages of PL/!L#

    Better Application Performance:PL/!L provides the capability to define a *bloc"* of programming

    statements, and can transmit this bloc" to an +racle database as a unit of wor"# hen multipleL$ statements are part of a PL/!L bloc", there are still only two networ" trips# $his improvessystem response time by decreasing the amount of networ" and performance overhead that isincurred with an approach where each L$ statement processes individually#

    Productivity, Portability, and Security: PL/!L stored procedures run on a server instead of aclient computer# $his means that the procedures can be secured from tampering by unscrupuloushac"ers by restricting access through the use of standard +racle database security# onsider atypical business requirement to update a customer order# .nstead of granting access to the customerorder table, you can grant access to a procedure that has been coded to update the table#

    PL/SQL BLOCK S!"C"!#:PL/!L bloc"s combine statements that represent a single logical tas"#hen the PL/!L engine is located on the server, the entire PL/!L bloc" is passed to the PL/!L engineon the +racle server# PL/!L bloc"s can be divided into two groups& namedand anonymous# 0amed bloc"sare used when creating subroutines# ubroutines include procedures and functions# nonymous PL/!Lbloc"s, as you have probably guessed, do not have names# s a result, they cannot be stored in thedatabase and referenced later#

  • 8/10/2019 Lab on Plsql

    2/7

    $ow a PL/SQL Pro%ram #&ecute':n anonymous bloc" e%ecutes by first sending the bloc" to the PL/!L engine on the server where it

    is compiled# .n contrast, a named PL/!L bloc" is compiled only at the time of its creation, or if it has beenmodified# $he compilation process includes syntax checking, binding, and p-code generation# ynta%

    chec"ing involves chec"ing PL/!L code for synta% or compilation errors# .f errors e%ist, the programmercorrects them and when a clean compile is achieved, the compiler assigns a storage address to programvariables that are used to hold data for +racle# $his process is called binding#

    fter binding, p-code is generated for the PL/!L bloc"# P-code is a list of instructions to thePL/!L engine# 1or named PL/!L bloc"s, p-code is stored in the database, and it is used the ne%t time theprogram is e%ecuted# fter the process of compilation completes, the status for a named PL/!L bloc" is setto 2L.3, and the status is also stored in the database# .f the compilation process is not successful, thestatus for a named PL/!L bloc" is set to .02L.3#

    Structure of a PLSQL pro%ram:DECLARE Declaration statementsBEGIN

    Executable statementsEXCEPTION Exception-an!lin" statementsEND#

    /4 3eclare and %ception parts are optional# very statement must be terminated by semicolon# .dentifiersstart with alphabets# omments as shown# 5eserved words cannot be used# tatements may span multiplelines4/#(A)PL#To !ispla$ output o% Pl&'(L on s)lplus screen %irst execute belo* statement'(L+ 'ET 'ER,EROTPT ON#.rite te %ollo*in" co!e in te '(LPlus prompt/

    '(L+

    DECLARE num0a"e N1BER234 56 78# -- assi"n 9alue to 9ariableBEGIN num0a"e 56 78# DB1'0OTPT/PT0LINE2:1$ a"e is5 : ;; TO0C

  • 8/10/2019 Lab on Plsql

    3/7

    3$ 3ates $odays3ate 3$:

    ?++L0 $5= / 1L / 0=LL values +rder1lag ?++L0:

    L+?(.t has four data types& ?1.L,?L+?, L+? and 0L+?)

    Large +bects >essage L+?:

    B$6P ssumes the data type of thedatabase field

    ustddress customer#caddB$6P:

    B5+$6P ssumes the data type of adatabase row

    ust+rder5ecord custAorderB5+$6P:

    ?5 and uses the assignment operator (&C) to assign an initial value of

  • 8/10/2019 Lab on Plsql

    4/7

    e%ceptions # .f you want to catch other e%ceptions (other predefined e%ceptions you donFt "now but you wanta default action for) then you can use the default e%ception handler +$'5#

    EXCEPTION.

  • 8/10/2019 Lab on Plsql

    5/7

    &HILE LOOP

    S+L2 DECLARE 90Counter N1BER 56 =#

    BEGIN .

  • 8/10/2019 Lab on Plsql

    6/7

    $he following statement creates a temporary table named ingredients_new.

    CREATE TABLE ingredients_new AS SELECT * FROM ingredients;

    EXAMPLE:

    $he program ma"es use of the !LB1+=03 and !LB5++=0$ attributes# $his e%ample updatesunitprice for a given ingredient id#

    SQL-DECLARE

    unit_price ingredients_new.unitprice%type;

    old_price ingredients_new.unitprice%type;

    ingredient ingredients_new.ingredientid%type :='&ingredient';

    BEGIN

    select unitprice into unit_price from ingredients_new where ingredientid=ingredient;

    IF SQL%NOTFOUND THEN

    DBMS_OUTPUT.PUT_LINE('Ingredient ' || ingredient || ' not found');

    else

    old_price:=unit_price;unit_price:=unit_price+ unit_price*0.1;

    UPDATE ingredients_new set unitprice=unit_price where ingredientid=ingredient;

    IF SQL%FOUND THEN -- ingredient updated

    DBMS_OUTPUT.PUT_LINE('Updated unitprice for ' || ingredient ||' from '||

    TO_CHAR(old_price) || ' to ' || TO_CHAR(unit_price));

    END IF;

    END IF;

    EXCEPTION

    WHEN NO_DATA_FOUND THEN

    DBMS_OUTPUT.PUT_LINE('no ingredient found');

    WHEN TOO_MANY_ROWS THEN

    DBMS_OUTPUT.PUT_LINE('Too many rows selectd');

    END;

    /EXAMPLE:

    $his e%ample updates deletes all ingredients e%cept $5# $he success of this is reported using attributes#$he program ma"es use of the !LB1+=03 and !LB5++=0$ attributes#SQL-BEGIN

    DELETE FROM ingredients_new WHERE ingredientid 'WATER';

    IF SQL%FOUND THEN -- ingredients were deleted

    DBMS_OUTPUT.PUT_LINE('Number deleted: ' || TO_CHAR(SQL%ROWCOUNT));

    END IF;

    END;

    /

    #&plicit Cur'or'$he set of rows returned by a query often includes many rows# hen a query returns more than onerow, you need to declare an e%plicit cursor in order to process the rows# 3eclare cursors in the 3L5section of a PL/!L bloc" program# %plicit cursors are processed by following a four'tepmodel#

  • 8/10/2019 Lab on Plsql

    7/7

    FETCH INTO ;

    D) 1inally, a cursor is disabled with the L+ statement# $his also causes the result set to becomeundefined# closed cursor cannot be reopened# $he general format of the L+ statement is&

    CLOSE ;

    0e%t lab continues with e%plicit cursors with e%amples#

    ---------------------------------------------------------------------