sql pl sql essentials

Upload: sranjeet

Post on 07-Apr-2018

308 views

Category:

Documents


3 download

TRANSCRIPT

  • 8/6/2019 SQL Pl SQL Essentials

    1/29

    SQL /PLSQL ESSENTIALS

    Presenter :

    Ranjeet Sharma

  • 8/6/2019 SQL Pl SQL Essentials

    2/29

    What is SQL?

    When a user wants to get some information

    from a database file, he can issue a query.

    A query is a userrequest to retrieve data

    or information with a certain condition.

    SQL is a query language that allows user tospecify the conditions.

  • 8/6/2019 SQL Pl SQL Essentials

    3/29

    General StructureGeneral Structure

    DISTINCT will eliminate duplication in the output

    while ALL will keep all duplicated rows.

    condition can be :

    (1) an inequality, or

    (2) a string comparison

    using logical operators AND, OR, NOT.

    SELECTSELECT [ALL / DISTINCT][ALL / DISTINCT] expr1expr1 [AS[AS col1col1],], expr2expr2[AS[AS col2col2]] ;;

    FROMFROM tablenametablename WHEREWHERE conditioncondition

  • 8/6/2019 SQL Pl SQL Essentials

    4/29

    GroupingGrouping

    SELECT ...... FROM ...... WHERESELECT ...... FROM ...... WHEREconditioncondition ;;

    GROUP BYGROUP BY groupexprgroupexpr [HAVING[HAVING requirementrequirement]]

    Group functions:Group functions:

    COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

    groupexpr specifies the related rows to be grouped

    as one entry. Usually it is a column.

    WHERE condition specifies the condition of

    individual rows before the rows are group.

    HAVING requirement specifies the condition

    involving the whole group.

  • 8/6/2019 SQL Pl SQL Essentials

    5/29

    Natural JoinNatural Join

    AA Natural JoinNatural Join is a join operation that joins twois a join operation that joins two

    tables bytables by their common column. This operationtheir common column. This operation

    is similar to the setting relation of two tables.is similar to the setting relation of two tables.

    SELECT a.comcol, a.SELECT a.comcol, a.col1col1, b., b.col2col2,, expr1expr1,, expr2expr2 ;;

    FROMFROM table1table1 a,a, table2table2b ;b ;

    WHERE a.WHERE a.comcolcomcol= b.= b.comcolcomcol

  • 8/6/2019 SQL Pl SQL Essentials

    6/29

    AnAn Outer JoinOuter Join is a join operation that includesis a join operation that includes

    rows that have a match, plus rows that do notrows that have a match, plus rows that do not

    have a match in the other table.have a match in the other table.

    Outer JoinOuter Join

  • 8/6/2019 SQL Pl SQL Essentials

    7/29

    Programming in Oracle

    with PL/SQL

    Procedural Language Extension to SQL

  • 8/6/2019 SQL Pl SQL Essentials

    8/29

    PL/SQL Blocks PL/SQL code is built of Blocks, with a unique

    structure.

    There are two types of blocks in PL/SQL:

    1. Anonymous Blocks: have no name (like scripts)

    can be written and executed immediately in SQLPLUS

    2. Named Blocks:

    Procedures

    Functions

  • 8/6/2019 SQL Pl SQL Essentials

    9/29

    Anonymous Block Structure:

    DECLARE (optional)/* Here you declare the variables you will use in this block */

    BEGIN (mandatory)

    /* Here you define the executable statements (what theblock DOES!)*/

    EXCEPTION (optional)/* Here you define the actions that take place if an exception

    is thrown during the run of this block */

    END; (mandatory)/

    Always put a new line with only a / at

    the end of a block! (This tells Oracle

    to run the block)

    A correct completion of a block will

    generate the following message:

    PL/SQL procedure successfully

    completed

  • 8/6/2019 SQL Pl SQL Essentials

    10/29

    Creating a Cursor

    We create a Cursor when we want to go over a resultof a query (like ResultSet in JDBC)

    Syntax Example:

    DECLAREcursor c is select * from sailors;

    sailorData sailors%ROWTYPE;

    BEGINopen c;

    fetch c into sailorData;

    sailorData is a

    variable that canhold a ROW

    from the sailors

    table

    Here the first

    row of sailors is

    inserted into

    sailorData

  • 8/6/2019 SQL Pl SQL Essentials

    11/29

    Explicit Cursor Attributes

    Obtain status information about a cursor.

    Attribute Type Description

    %ISOPEN Boolean Evaluates to TRUE if the cursor

    is open.

    %NOTFOUND Boolean Evaluates to TRUE if the most

    recent fetch does not return a row.

    %FOUND Boolean Evaluates to TRUE if the most

    recent fetch returns a row;

    complement of %NOTFOUND

    %ROWCOUNT Number Evaluates to the total number of

    rows returned so far.

  • 8/6/2019 SQL Pl SQL Essentials

    12/29

    Loops: Simple Loop

    DECLARE

    i number_table.num%TYPE := 1;BEGINLOOPINSERT INTO number_tableVALUES(i);i := i + 1;EXIT WHEN i > 10;

    END LOOP;END;

    create table number_table(

    num NUMBER(10));

  • 8/6/2019 SQL Pl SQL Essentials

    13/29

    Loops: Simple Cursor Loop

    DECLARE

    cursor c is select * from number_table;cVal c%ROWTYPE;BEGINopen c;LOOP

    fetch c into cVal;EXIT WHEN c%NOTFOUND;insert into doubles values(cVal.num*2);

    END LOOP;END;

    create table number_table(

    num NUMBER(10));

  • 8/6/2019 SQL Pl SQL Essentials

    14/29

    Printing Output

    You need to use a function in the DBMS_OUTPUT

    package in order to print to the output

    If you want to see the output on the screen, you must

    type the following (before starting):

    set serveroutput on format wrapped size 1000000

    Then print using

    dbms_output. put_line(your_string);

    dbms_output.put(your_string);

  • 8/6/2019 SQL Pl SQL Essentials

    15/29

    Trapping Exceptions

    Here we define the actions that should happen

    when an exception is thrown.

    Example Exceptions:

    NO_DATA_FOUND

    TOO_MANY_ROWS

    ZERO_DIVIDE

  • 8/6/2019 SQL Pl SQL Essentials

    16/29

    DECLAREnum_row number_table%ROWTYPE;

    BEGINselect *

    into num_rowfrom number_table;dbms_output.put_line(1/num_row.num);

    EXCEPTIONWHENNO_DATA_FOUND THEN

    dbms_output.put_line('No data!');

    WHEN TOO_MANY_ROWS THENdbms_output.put_line('Too many!');WHEN OTHERS THEN

    dbms_output.put_line(Error);end;

  • 8/6/2019 SQL Pl SQL Essentials

    17/29

    User-Defined ExceptionDECLARE

    e_number1 EXCEPTION;cnt NUMBER;

    BEGINselect count(*)into cnt

    from number_table;

    IF cnt = 1 THEN RAISE e_number1;ELSE dbms_output.put_line(cnt);END IF;

    EXCEPTIONWHEN e_number1 THEN

    dbms_output.put_line('Count = 1');

    end;

  • 8/6/2019 SQL Pl SQL Essentials

    18/29

    Functions and Procedures

    Up until now, our code was in an anonymousblock

    It was run immediately

    It is useful to put code in a function orprocedure so it can be called several times

    Once we create a procedure or function in a

    Database, it will remain until deleted (like atable).

  • 8/6/2019 SQL Pl SQL Essentials

    19/29

    Creating a Function

    Almost exactly like creating a procedure, but

    you supply a return type

    CREATE [OR REPLACE] FUNCTIONfunction_name

    [(parameter1 [mode1] datatype1,parameter2[mode2] datatype2,

    . . .)]RETURN datatypeIS|ASPL/SQL Block;

  • 8/6/2019 SQL Pl SQL Essentials

    20/29

    Triggers

    Triggers are special procedures which we wantactivated when someone has performed someaction on the DB.

    For example, we might define a trigger that isexecuted when someone attempts to insert arow into a table, and the trigger checks thatthe inserted data is valid.

  • 8/6/2019 SQL Pl SQL Essentials

    21/29

    Trigger types

    1) Row level trigger - An event is triggered for

    each row upated, inserted or deleted.

    2) Statement level trigger - An event is

    triggered for each sql statement executed.

  • 8/6/2019 SQL Pl SQL Essentials

    22/29

    Trigger Syntax

    CREATE [OR REPLACE ] TRIGGER trigger_name{BEFORE | AFTER } {INSERT [OR] | UPDATE [OR] |DELETE}

    [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n]

    [FOR EACH ROW] WHEN (condition)

    BEGIN

    --- sql statements

    END;

  • 8/6/2019 SQL Pl SQL Essentials

    23/29

    1) BEFORE UPDATE, Statement Level: This triggerwill insert a record into the table 'product_check'before a sql update statement is executed, at the

    statement level.

    CREATEorREPLACE TRIGGERBefore_Update_Stat_productBEFOREUPDATE

    ONproduct Begin INSERT INTO product_check

    Values('Beforeupdate,statementlevel',sysdate);

    END; /

  • 8/6/2019 SQL Pl SQL Essentials

    24/29

    2) BEFORE UPDATE, Row Level: This trigger willinsert a record into the table 'product_check'

    before each row is updated.

    CREATEorREPLACE TRIGGERBefore_Upddate_Row_productBEFOREUPDATEONproductFOR EACH ROW

    BEGIN

    INSERT INTO product_check Values('Before

    update rowlevel',sysdate); END;

    /

  • 8/6/2019 SQL Pl SQL Essentials

    25/29

    PL/SQL in Web Applications

    mod_plsql :Plug in to Oracle HTTP Server, an

    implementation of pl sql gateway

    mod_plsql maps Web client requests to

    PL/SQL stored subprograms over HTTP

  • 8/6/2019 SQL Pl SQL Essentials

    26/29

    MOD_PLSQL was formerly called the Oracle PL/SQL Cartridge and OWA

    (Oracle Web Agent).

    mod_plsql maps Web client requests to PL/SQL stored subprograms over HTTP

    The mod_plsql plug-in enables you to use PL/SQL stored subprograms to

    process HTTP requests and generate responses

    Obtain info of http requestGenerates HTTP Headers

    And Browser cookies

    invoke a PL/SQL storedsubprogram through an

    HTTP listener

  • 8/6/2019 SQL Pl SQL Essentials

    27/29

    CREATE OR REPLACE PROCEDURE print_employees IS CURSOR emp_cursor IS

    SELECT last_name, first_name

    FROM hr.employees

    ORDER BY last_name;

    BEGIN HTP.PRINT('');

    HTP.PRINT('');

    HTP.PRINT('');

    HTP.PRINT('List of Employees');

    HTP.PRINT('');

    HTP.PRINT('');

    HTP.PRINT('List of Employees');

    HTP.PRINT('');

    HTP.PRINT('');

    HTP.PRINT('Last Name');

    HTP.PRINT('First Name');

    HTP.PRINT('');

    FOR emp_record IN emp_cursor LOOP

    HTP.PRINT('');

    HTP.PRINT('' || emp_record.last_name || '');

    HTP.PRINT('' || emp_record.first_name || '');

    END LOOP; HTP.PRINT('');

    HTP.PRINT('');

    HTP.PRINT('');

    END;

  • 8/6/2019 SQL Pl SQL Essentials

    28/29

    http://host:port/plsql/print_employees

    http://example.

    com:8080/plsql/print_employees

    The Web browser returns an HTML page with

    a table that includes the first and last name of

    every employee in the hr.employees table.

  • 8/6/2019 SQL Pl SQL Essentials

    29/29

    Questions / Discussions?