Basic Plsql

download Basic Plsql

of 57

Transcript of Basic Plsql

  • 8/2/2019 Basic Plsql

    1/57

    1

    Introduction to PL/SQL

  • 8/2/2019 Basic Plsql

    2/57

    2

    Fundamentals of PL/SQL

    Full-featured programming language

    An interpreted language Type in editor, execute in SQL*Plus

  • 8/2/2019 Basic Plsql

    3/57

    3

    Variables and Data Types

    VariablesUsed to store numbers, character

    strings, dates, and other data values

    Avoid using keywords, table names andcolumn names as variable names

    Must be declared with data type beforeuse: variable_namedata_type_declaration;

  • 8/2/2019 Basic Plsql

    4/57

    4

    Scalar Data Types

    Represent a single value

  • 8/2/2019 Basic Plsql

    5/57

    5

  • 8/2/2019 Basic Plsql

    6/57

    6

    Composite and Reference Variables

    Composite variablesRECORD: contains multiple scalar values, similar to a table

    record

    TABLE: tabular structure with multiple columns and rowsVARRAY: variable-sized array

    Reference variablesDirectly reference a specific database field or record and assume

    the data type of the associated field or record%TYPE: same data type as a database field%ROWTYPE: same data type as a database record

  • 8/2/2019 Basic Plsql

    7/57

    7

    PL/SQL Program Blocks

  • 8/2/2019 Basic Plsql

    8/57

    8

    Arithmetic Operators

  • 8/2/2019 Basic Plsql

    9/57

    9

    Assignment Statements

    Assigns a value to a variable

    variable_name := value; Value can be a literal:

    current_s_first_name := 'John';

    Value can be another variable:current_s_first_name := s_first_name;

  • 8/2/2019 Basic Plsql

    10/57

    10

    Executing a PL/SQL

  • 8/2/2019 Basic Plsql

    11/57

    11

    PL/SQL Data Conversion

    Functions

  • 8/2/2019 Basic Plsql

    12/57

    12

    Manipulating Character

    Strings To concatenate two strings in PL/SQL, you use the

    double bar (||) operator:new_string := string1 || string2;

    To remove blank leading spaces use the LTRIM function:string := LTRIM(string_variable_name);

    To remove blank trailing spaces use the RTRIM function:string := RTRIM(string_variable_name);

    To find the number of characters in a character string

    use the LENGTH function:string_length := LENGTH(string_variable_name);

  • 8/2/2019 Basic Plsql

    13/57

    13

    Manipulating Character

    Strings To change case, use UPPER, LOWER, INITCAP

    INSTR function searches a string for a specific

    substring:start_position := INSTR(original_string, substring);

    SUBSTR function extracts a specific number ofcharacters from a character string, starting at a

    given point:extracted_string := SUBSTR(string_variable,

    starting_point, number_of_characters);

  • 8/2/2019 Basic Plsql

    14/57

    14

    PL/SQL Decision Control

    Structures Use IF/THEN structure to execute code if condition is true

    IF condition THENcommands that execute if condition is TRUE;

    END IF;

    If condition evaluates to NULL it is considered false Use IF/THEN/ELSE to execute code if condition is true or false

    IF condition THENcommands that execute if condition is TRUE;

    ELSE

    commands that execute if condition isF

    ALSE

    ;END IF;

    Can be nested be sure to end nested statements

  • 8/2/2019 Basic Plsql

    15/57

    15

    PL/SQL Decision Control

    Structures Use IF/ELSIF to evaluate many conditions:

    IF condition1 THEN

    commands that execute if condition1 is TRUE;

    ELSIF condition2 THENcommands that execute if condition2 is TRUE;

    ELSIF condition3 THENcommands that execute if condition3 is TRUE;

    ...ELSE

    commands that execute if none of theconditions are TRUE;

    END IF;

  • 8/2/2019 Basic Plsql

    16/57

    16

    Complex Conditions

    Created with logical operators AND, ORand NOT

    AND is evaluated before OR

    Use () to set precedence

  • 8/2/2019 Basic Plsql

    17/57

    17

    Loops

    Program structure that executes a series ofprogram statements, and periodically evaluatesan exit condition to determine if the loop shouldrepeat or exit

    Pretest loop: evaluates the exit condition beforeany program commands execute

    Posttest loop: executes one or more program

    commands before the loop evaluates the exitcondition for the first time PL/SQL has 5 loop structures

  • 8/2/2019 Basic Plsql

    18/57

    18

    The LOOP...EXIT Loop

    LOOP

    [program statements]

    IF condition THEN

    EXIT;

    END I

    F;

    [additional program statements]

    END LOOP

  • 8/2/2019 Basic Plsql

    19/57

    19

    The LOOP...EXIT WHEN Loop

    LOOP

    program statementsEXIT WHEN condition;

    END LOOP;

  • 8/2/2019 Basic Plsql

    20/57

    20

    The WHILE...LOOP

    WHILE condition LOOP

    program statementsEND LOOP;

  • 8/2/2019 Basic Plsql

    21/57

    21

    The Numeric FOR Loop

    FOR counter_variable IN start_value

    .. end_valueLOOP

    program statements

    END LOOP;

  • 8/2/2019 Basic Plsql

    22/57

    22

    Cursors

    Pointer to a memory location that

    the DBMS uses to process a SQLquery

    Use to retrieve and manipulatedatabase data

  • 8/2/2019 Basic Plsql

    23/57

    23

    ImplicitCursor

    Executing a SELECT query creates an implicitcursor

    To retrieve it into a variable use IN

    TO

    : SELECT field1, field2, ...INTO variable1, variable2, ...FROM table1, table2, ...WHERE join_ conditions

    AND search_condition_to_retrieve_1_record; Can only be used with queries that return

    exactly one record

  • 8/2/2019 Basic Plsql

    24/57

    24

    ExplicitCursor

    Use for queries that return

    multiple records or no records

    Must be explicitly declared andused

  • 8/2/2019 Basic Plsql

    25/57

    25

    Using an ExplicitCursor Declare the cursor

    CURSOR cursor_name IS select_query;

    Open the cursor

    OPEN cursor_name; Fetch the data rows

    LOOP

    FETCH cursor_name INTO variable_name(s);

    EXIT WHEN cursor_name%NOTFOUND; Close the cursor

    CLOSE cursor_name;

  • 8/2/2019 Basic Plsql

    26/57

    26

    Cursor FOR Loop

    Automatically opens the cursor, fetchesthe records, then closes the cursor

    FOR variable_name(s) IN cursor_nameLOOP

    processing commands

    END LOOP; Cursor variables cannot be used outside

    loop

  • 8/2/2019 Basic Plsql

    27/57

    27

    Handling Runtime Errorsin PL/SQL Programs

    Runtime errors cause exceptions Exception handlers exist to deal with different

    error situations Exceptions cause program control to fall to

    exception section where exception is handled

  • 8/2/2019 Basic Plsql

    28/57

    28

    Predefined Exceptions

  • 8/2/2019 Basic Plsql

    29/57

    29

    Undefined Exceptions

    Less common errors Do not have predefined names

    Must declare your own name for theexception code in the declaration sectionDECLARE

    e_exception_name EXCEPTION;

    PRAGMAEXCEPTION_INIT(e_exception_name,

    -Oracle_error_code);

  • 8/2/2019 Basic Plsql

    30/57

    30

    User-Defined Exceptions

    Not a real Oracle error Use to enforce business rules

  • 8/2/2019 Basic Plsql

    31/57

    31

    Summary

    PL/SQL is a programming language for workingwith an Oracle database

    Scalar, composite and reference variables can beused

    The IF/THEN/ELSE decision control structureallows branching logic Five loop constructs allow repeating code Cursors are returned from queries and can be

    explicitly iterated over Exception handling is performed in the exceptionsection. User defined exceptions help to enforcebusiness logic

  • 8/2/2019 Basic Plsql

    32/57

    32

    Overview of PL/SQLStored Program Units

    Self-contained group of programstatements that can be used within a

    larger program. Easier to conceptualize, design, and debug Save valuable programming time because

    you can reuse them in multiple database

    applications Other PL/SQL programs can reference

    them

  • 8/2/2019 Basic Plsql

    33/57

    33

    Overview of PL/SQLStored Program Units

    Server-side program units stored inthe database as database objects andexecute on the database server

    Client-side program units stored in

    the file system of the clientworkstation and execute on the clientworkstation

  • 8/2/2019 Basic Plsql

    34/57

    34

    Types of Program Units

  • 8/2/2019 Basic Plsql

    35/57

    35

    Creating Stored Program Units

    Procedure: a program unit that canreceive multiple input parameters andreturn multiple output values or return nooutput values

    Function: a program unit that canreceive multiple input parameters, andalways returns a single output value.

  • 8/2/2019 Basic Plsql

    36/57

    36

  • 8/2/2019 Basic Plsql

    37/57

    37

  • 8/2/2019 Basic Plsql

    38/57

    38

    Parameter Declarations List

    Defines the parameters and declarestheir associated data types

    Enclosed in parentheses

    Separated by commas

  • 8/2/2019 Basic Plsql

    39/57

    39

    Parameter Declarations List

    Parameter mode describes how the programunit can change the parameter value:

    IN

    - specifies a parameter that is passed to theprogram unit as a read-only value that the programunit cannot change.

    OUT - specifies a parameter that is a write-only valuethat can appear only on the left side of an assignment

    statement in the program unitINOUT - specifies a parameter that is passed to the

    program unit, and whose value can also be changedwithin the program unit

  • 8/2/2019 Basic Plsql

    40/57

    40

    Calling a Stored Procedure

    From SQL*Plus command line:

    EXEC

    UTE

    procedure_name(parameter1_value, parameter2_value,...);

    From PL/SQL program:

    Omit execute command

  • 8/2/2019 Basic Plsql

    41/57

    41

    Calling a Function

    variable_name :=function_name(parameter1, parameter2,

    ...); Select function_name(parameter1,

    parameter2, ...)

    from dual;

  • 8/2/2019 Basic Plsql

    42/57

    42

    Packages

    Another way to make PL/SQL programunits available to multiple applications

    A code library that contains relatedprogram units and variables

    Stored in the database and executes on

    the database server

  • 8/2/2019 Basic Plsql

    43/57

    43

    Package Specification

    Also called package header Declares package objects, including

    variables, cursors, procedures, andfunctions, Use to declare public variables:

    Remain in memory after the programs that

    declare and reference them terminateDeclared in the DECLARE section of a packageReferenced same as private variables

  • 8/2/2019 Basic Plsql

    44/57

    44

    Package Specification

  • 8/2/2019 Basic Plsql

    45/57

    45

    Package Header

    Package_name identifies the package

    Must adhere to the Oracle Naming Standard

    Declare the package objects in any order

    Package can consist of just variabledeclarations, or it can consist of just

    procedure or function declarations

  • 8/2/2019 Basic Plsql

    46/57

    46

    Procedure and FunctionDeclarations

    Declare a procedure:PROCEDURE procedure_name

    (parameter1 parameter1_data_type,parameter2 parameter2_data_type, ...);

    Declare a function:FUNCTION function_name

    (parameter1 parameter1_data_type,parameter2 parameter2_data_type, ...)

    RETURN return_datatype;

  • 8/2/2019 Basic Plsql

    47/57

    47

    Package Body

    Contains the implementation ofdeclared procedures and functions

    Specification comes before body

    Optional: sometimes a packagecontains only variable or cursor

    declarations, and no procedure orfunction declarations

  • 8/2/2019 Basic Plsql

    48/57

    48

    Package Body

    Package_name in the package body must be the sameas package_name in the package specification

    Variables that you declare at the beginning of the

    package body are private to the package Each package program unit has its own declaration

    section and BEGIN and END statements

    Each program unit declared in the package body must

    have a matching program unit forward declaration in thepackage specification, with an identical parameter list

  • 8/2/2019 Basic Plsql

    49/57

    49

    Creating a Package Header

  • 8/2/2019 Basic Plsql

    50/57

    50

    Creating a Package Body

  • 8/2/2019 Basic Plsql

    51/57

    51

    Using Package Objects

    Must preface the item with thepackage name:

    package_name.item_name.

    To grant other users the privilege toexecute a package:

    GRANT EXECUTEON package_name TO

    username;

  • 8/2/2019 Basic Plsql

    52/57

    52

    Database Triggers

    Program units that execute in response tothe database events of inserting,updating, or deleting a record

    Different from form triggers Useful for maintaining integrity constraints

    and audit information

    Cannot accept input parameters

    Executes only when its triggering eventoccurs

  • 8/2/2019 Basic Plsql

    53/57

    53

    Trigger Properties

    Trigger timing:

    Defines whether a trigger fires before orafter the SQL statement executes

    Can have the values BEFORE or AFTER

    Trigger statement:

    Defines the type of SQL statement thatcauses a trigger to fire

    Can be INSERT, UPDATE, or DELETE

  • 8/2/2019 Basic Plsql

    54/57

    54

    Trigger Properties

    Trigger level:Defines whether a trigger fires once for each

    triggering statement or once for each row affected bythe triggering statement

    Can have the values

    ROWor STAT

    EMEN

    TStatement-level triggers fire once, either before or

    after the SQL triggering statement executes.

    Row-level triggers fire once for each row affected bythe triggering statement

    Use :OLD.fieldname to reference previous value

    Use :NEW.fieldname to reference changed value

  • 8/2/2019 Basic Plsql

    55/57

    55

    Creating Database Triggers

  • 8/2/2019 Basic Plsql

    56/57

    56

    Database Trigger Header

    Trigger_name must follow Oracle NamingStandard

    Join statement types using the OR

    operator to fire for multiple statementtypes (INSERT OR UPDATE)

    WHEN (condition) clause:

    Trigger will fire only for rows that satisfy aspecific search condition

    WHENOLD.grade IS NOT NULL;

  • 8/2/2019 Basic Plsql

    57/57

    57

    Database Trigger Body

    Contains the commands that executewhen the trigger fires

    PL/SQL code block that contains the usual

    declaration, body, and exception sections Cannot contain transaction control

    statements

    Reference the

    NEWand

    OLD field valuesonly in a row-level trigger