PL/SQL - Oracle's Procedural Language Extension to SQL

Embed Size (px)

Citation preview

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    1/32

    ISAD211

    PL/SQL

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    2/32

    ISAD211

    PL/SQL - Oracle's ProceduralLanguage extension to SQL

    4 loosely based on Ada4 includes (inter alia)

    4 block structure4 datatypes (including Boolean)4 variables & constants4 assignment statement4 conditional statements

    4 if .. then4 if .. then .. else4 if .. then .. elsif

    4 loops4 basic loop (needs exit condition)4 for loop4 while loop

    4 allows most SQL commands to be embedded

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    3/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    4/32

    ISAD211

    Anonymous block examples

    BEGIN DBMS_OUTPUT.PUT_LINE('Hello World!');END;

    DECLARE v_day_of_week VARCHAR2(12); -- local variableBEGIN SELECT TO_CHAR(SYSDATE, 'Day') INTO v_day_of_week FROM sys.dual; IF v_day_of_week IN ('Saturday', 'Sunday') THEN -- note use of extra quote in string DBMS_OUTPUT.PUT_LINE('It''s the weekend!'); ELSE DBMS_OUTPUT.PUT_LINE('Too bad - it''ll be the weekend

    soon'); END IF;END; SET SERVEROUTPUT ON

    to get output fromDBMS_OUTPUT.PUT_LINE

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    5/32

    ISAD211

    Stored programs

    4Code stored in the database andexecuted on the server4advantages of DB approach

    4 store once, use many4backup/recovery

    4access control

    4Multiple use by multiple

    users/applications GRANT EXECUTE ON TO

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    6/32

    ISAD211

    Stored procedure

    CREATE OR REPLACE PROCEDURE TGITW IS v_day_of_week VARCHAR2(12); -- DECLARE not used hereBEGIN SELECT TO_CHAR(SYSDATE, 'Day') INTO v_day_of_week FROM sys.dual; IF v_day_of_week IN ('Saturday', 'Sunday') THEN DBMS_OUTPUT.PUT_LINE('It''s the weekend!'); ELSE DBMS_OUTPUT.PUT_LINE('Too bad - it''ll be the weekend soon'); END IF;END;

    -- SQL*Plusexec TGITW

    -- SQL*Plus and SQL DeveloperBEGIN TGITW;END;

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    7/32ISAD211

    Stored function

    CREATE OR REPLACE FUNCTION get_age(p_birth_date IN DATE) -- INput parameter RETURN INTEGER IS -- data type of result v_age INTEGER;BEGIN SELECT TRUNC(MONTHS_BETWEEN(SYSDATE, p_birth_date)/12) INTO v_age FROM sys.dual; RETURN(v_age); -- result of function

    END;

    GRANT EXECUTE ON get_age TO PUBLIC;

    SELECT sname, bdate, brian.get_age(bdate) ageFROM rearp.studentORDER BY age DESC, bdate ASC;

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    8/32ISAD211

    Also available

    SELECT brian.valid_postcode('PL4 8AA')

    FROM sys.dual;

    TRUE

    SELECT brian.valid_postcode('PL0 8AA')

    FROM sys.dual;

    FALSE

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    9/32ISAD211

    Cursors

    4 SQL query delivers an indivisible SET ofrows

    4Cursor allows row by row processing of

    the result set of a query4 Think of a cursor as a local table of

    results4Read one record or row at a time4Do something with it

    4

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    10/32ISAD211 1

    Cursor operations

    4DECLARE4specify query to populate cursor

    4

    OPEN4run query to populate cursor

    4FETCH4

    get a 'row' from the cursor4CLOSE

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    11/32ISAD211 1

    DECLARE title_cur cursor

    CURSOR title_cur IS

    SELECT title

    FROM books;4

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    12/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    13/32

    ISAD211 1

    FETCH title_cur INTO v_title;

    Serpent's Reach

    Faded Sun, Kesrith, The

    Faded Sun, Shon'jir, The

    Titans, The

    Black Tulip, The

    Serpent's Reach

    v_title

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    14/32

    ISAD211 1

    FETCH title_cur INTO v_title;

    Serpent's Reach

    Faded Sun, Kesrith, The

    Faded Sun, Shon'jir, The

    Titans, The

    Black Tulip, The

    Faded Sun, Kesrith, The

    v_title

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    15/32

    ISAD211 1

    FETCH title_cur INTO v_title;

    Serpent's Reach

    Faded Sun, Kesrith, The

    Faded Sun, Shon'jir, The

    Titans, The

    Black Tulip, The

    Faded Sun, Shon'jir, The

    v_title

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    16/32

    ISAD211 1

    FETCH title_cur INTO v_title;

    Serpent's Reach

    Faded Sun, Kesrith, The

    Faded Sun, Shon'jir, The

    Titans, The

    Black Tulip, The

    Titans, The

    v_title

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    17/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    18/32

    ISAD211 1

    EXIT WHEN title_cur

    %NOTFOUND;

    Serpent's Reach

    Faded Sun, Kesrith, The

    Faded Sun, Shon'jir, The

    Titans, The

    Black Tulip, The

    v_title

    No rows left in cursor

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    19/32

    ISAD211 1

    Cursor example

    DECLARE v_new_title VARCHAR2(60); v_title VARCHAR2(60); v_length INTEGER; v_char CHAR(1); CURSOR c_title IS SELECT title FROM books;BEGIN OPEN c_title; LOOP FETCH c_title INTO v_title; EXIT WHEN c_title%NOTFOUND; v_length := LENGTH(v_title); v_new_title := ''; FOR i IN 1..v_length LOOP v_char := SUBSTR(v_title, i, 1);

    IF UPPER(v_char) IN ('A', 'E', 'I', 'O', 'U') THEN v_char := '*'; END IF; v_new_title := v_new_title||v_char; END LOOP; DBMS_OUTPUT.PUT_LINE(v_new_title); END LOOP; CLOSE c_title;

    END;

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    20/32

    ISAD211 2

    Listing stored code in

    SQL Developer

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    21/32

    ISAD211 2

    PL/SQL exception handling

    4Enables bulletproofing of code tohandle run-time errors and retainprocessing control

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    22/32

    ISAD211 2

    Example (modified from Oracledocumentation)

    DECLARE v_pe_ratio NUMBER(3,1);BEGIN SELECT price / earnings -- potential division-by-zero

    error INTO v_pe_ratio

    FROM stocks WHERE symbol = 'XYZ'; INSERT INTO stats (symbol, ratio) VALUES ('XYZ', v_pe_ratio); COMMIT; EXCEPTION -- exception handlers begin WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error

    INSERT INTO stats (symbol, ratio) VALUES ('XYZ', NULL); COMMIT; WHEN OTHERS THEN -- handles all other errors ROLLBACK;END; -- exception handlers and block end here

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    23/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    24/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    25/32

    ISAD211 2

    Database triggers revisited

    4coded in PL/SQL

    4critical for data integrity

    4server-side integrity ensuresmore robust database than

    client-side validation4

    4

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    26/32

    ISAD211 2

    Client-side integrity

    databaseapplication

    integrityche

    cks

    database is

    vulnerable

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    27/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    28/32

    ISAD211 2

    Issues

    4Data sent to the server before beingchecked for integrity increasesnetwork traffic and server load

    4 Perform simple client-side 'belt andbraces' integrity checking, e.g. checkfor required fields

    4

    Opaque server error messages need tobe communicated sensibly to theapplication/user

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    29/32

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    30/32

    ISAD211 3

    Example trigger

    CREATE OR REPLACE TRIGGER trg_clientsBEFORE INSERT OR UPDATE OF dob ON clients FOR EACH ROWBEGIN IF INSERTING THEN SELECT seq_client_id.nextval

    INTO :NEW.client_id FROM sys.dual; END IF;IF MONTHS_BETWEEN(SYSDATE,:NEW.dob) < 18*12 THEN /* Issue error code (ORA-20000) and message */ RAISE_APPLICATION_ERROR(-20000, 'Client must be at

    least 18 years of age'); END IF;END;4

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    31/32

    ISAD211 3

    References

    4PLSQL by Example on Portal

    4

    4

    PL/SQL User's Guide andReference

    4

    Oracle10g Database ErrorMessages

    4

  • 8/14/2019 PL/SQL - Oracle's Procedural Language Extension to SQL

    32/32

    ISAD211 3

    Exercise

    4 Write a PL/SQL function (AVERAGE_PRICE) tocalculate the average retail price of books(rounded to the nearest penny) in theHarrington books table where the retail priceis above an amount specified as aparameter. You should use a cursor.

    4 Test your results against

    SELECTROUND(AVG(retail_price),2)

    FROM books