PLSQL Part1 Declaring Variables

download PLSQL Part1 Declaring Variables

of 33

Transcript of PLSQL Part1 Declaring Variables

  • 8/8/2019 PLSQL Part1 Declaring Variables

    1/33

    IBM SOLUTIONS DELIVERY INC.

    2008 IBM Corporation

    PL/SQL

    Part 1 - Declaring Variables

    Prepared by:

    Sherwin O. Bautista

  • 8/8/2019 PLSQL Part1 Declaring Variables

    2/33

    IBM SOLUTIONS DELIVERY INC.

    2

    Course Objectives

    After completing this course, trainees should be able to do thefollowing:

    Be on familiar terms with the basic PL/SQL block and its

    sections Will be able to describe the significance of variables in PL/SQL Declare PL/SQL variables Execute a PL/SQL block

  • 8/8/2019 PLSQL Part1 Declaring Variables

    3/33

    IBM SOLUTIONS DELIVERY INC.

    3

    DECLARE

    {code .... }

    BEGIN

    {code.}

    EXCEPTION

    {code.}

    END;

    PL/SQL Block Structure

    DECLARE - Optional

    Variables, cursors,user-defined exceptions

    BEGIN - Mandatory

    -- SQL statements-- PL/SQL statements

    EXCEPTION - Optional

    Actions to perform when error occurs

    END; - Mandatory

    A PL/SQL block consists of up to three sections: declarative (optional), executable(required), and exception handling (optional).

  • 8/8/2019 PLSQL Part1 Declaring Variables

    4/33

    IBM SOLUTIONS DELIVERY INC.

    4

    PL/SQL Block Structure

    A PL/SQL block consists of up to three sections: declarative (optional), executable(required), and exception handling (optional).

    Section Description Inclusion

    Declarative Contains all variables, constants, cursors, and user-define exceptions that are

    referenced in the executable and declarative sections

    Optional

    Executable Contains SQL statements to manipulate data in the database and PL/SQL statements

    to manipulate data in the block

    Mandatory

    Exception

    Handling

    Specifies the actions to perform when errors and abnormal conditions arise in the

    executable section

    Optional

  • 8/8/2019 PLSQL Part1 Declaring Variables

    5/33

    IBM SOLUTIONS DELIVERY INC.

    5

    Executing Statements and PL/SQL Blocks

    Place a semicolon (;) at the end of a SQL statement or PL/SQL control statement

    When the block is executed successfully, without unhandled errors or compile errors,the message output should be as follows:

    PL/SQL procedure successfully completed.

    Section keywords DECLARE, BEGIN, and EXCEPTION are not followed bysemicolons.

    END and all other PL/SQL statements require a semicolon to terminate thestatement.

    Note: Error is called an exception.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    6/33

    IBM SOLUTIONS DELIVERY INC.

    6

    [DECLARE]

    BEGIN

    -- statements

    [EXCEPTION]

    END;

    Block Types

    PROCEDUREnameIS

    BEGIN

    -- statements

    [EXCEPTION]

    END;

    FUNCTIONnameRETURNdatatype

    IS

    BEGIN

    -- statementsRETURNvalue;

    EXCEPTION

    END;

    Anonymous Procedure Functions

  • 8/8/2019 PLSQL Part1 Declaring Variables

    7/33

    IBM SOLUTIONS DELIVERY INC.

    7

    Block Types

    Anonymous Blocks:

    unnamed blocks

    declared at the point in an application where they are to be executed

    passed to the PL/SQL engine for execution at run time.

    can be embed within a pre-compiler program and with in iSQL*Plus.

    Subprograms: (declared as procedure or as functions)

    named PL/SQL blocks that can accept parameters and can be invoked.

    procedure use to perform an action

    function to compute a value.

    can store at the server or application level.

    Note: A function is similar to a procedure, except a function must return a value.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    8/33

    IBM SOLUTIONS DELIVERY INC.

    8

    Program Construct

    The program construct are available based on the environment in which they are executed.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    9/33

    IBM SOLUTIONS DELIVERY INC.

    9

    Use of Variables

    Variable can be use for the following:

    Temporary storage of data:

    While validating data input and for processing later in the data flow process, datacan be temporarily stored.

    Manipulation of stored values:

    Variables can be used for calculations and other data manipulations withoutaccessing the database.

    Reusability:

    Once variables declared, variables can be used repeatedly in an applicationsimply by referencing them in the other statements.

    Ease of maintenance:

    When using %TYPE and %ROWTYPE, you declare variables, basing thedeclarations on the definitions of database columns. If definition changes, thevariable declaration changes accordingly at run time.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    10/33

    IBM SOLUTIONS DELIVERY INC.

    10

    Handling Variables in PL/SQL

    Declare and Initialize Variables in the Declaration Section

    Declaring variables in the declarative part of any PL/SQL block, subprograms, orpackage will allocate storage space for a value and can reference by specify its datatype, and name of storage location. A variable must declare before referencing it inother statements.

    Assign New Values to Variables in the Executable Section

    In the executable section, the existing value of the variable is replaced with the newvalue that is assigned to the variable.

    Pass Values Into PL/SQLSubprograms through parameters

    There are three parameter modes.

    IN (default) -- use this parameter to pass values to the subprogram being

    called.

    OUT -- use this parameter to return values to the caller of a subprogram.

    IN OUT -- use this parameter to pass initial values to the subprogram beingcalled and to return updated values to the caller.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    11/33

    IBM SOLUTIONS DELIVERY INC.

    11

    Types of Variables

    PL/SQL supports four data type categories that can use for declaring variables, constant,and pointers.

    Scalar-- hold a single value.

    Composite-- records, allow group of fields to be defined and manipulated in PL/SQL blocks.

    Reference-- hold values called pointer that designate other program items (note: notcovered in this course).

    LOB (large objects)-- hold values called locators that specify the location of large objects (i.e. graphicimages) that are stored out of line.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    12/33

    IBM SOLUTIONS DELIVERY INC.

    12

    Types of Variables

    TRUE represents a Boolean value.

    08-AUG-08 represents a DATE

    The photograph represents a BLOB

    The text of a speech represents a LONG

    75232.09 represents a NUMBER data type with precision and scale.

    The movie represents a BFILE.

    The city name EASTWOOD represents a VARCHAR2

    Some illustration of variable data types:

  • 8/8/2019 PLSQL Part1 Declaring Variables

    13/33

    IBM SOLUTIONS DELIVERY INC.

    13

    Declaring PL/SQL Variables

    Examples:

    Syntax:

    identifier[CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

    DECLAREv_hiredate DATE;v_deptno NUMBER(2) NOT NULL := 10;v_location V ARCHAR2(13) := Eastwood;

    v_comm CONSTANT NUMBER := 1400;

  • 8/8/2019 PLSQL Part1 Declaring Variables

    14/33

    IBM SOLUTIONS DELIVERY INC.

    14

    Declaring PL/SQL Variables

    In the syntax:

    identifier is the name of the variable

    CONSTANT constrains the variable so that its value cannot change;constants must be initialized.

    data type is a scalar, composite, reference, orLOB data type.

    NOT NULL constrains the variable so that it must contain a value.(NOT NULL variables must be initialized).

    expr is any PL/SQL expression that can be a literal express or anothervariable or an expression involving operators and functions.

    Syntax:

    identifier[CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

  • 8/8/2019 PLSQL Part1 Declaring Variables

    15/33

    IBM SOLUTIONS DELIVERY INC.

    15

    Guidelines for Declaring PL/SQL Variables

    Name the identifier according to the same rules used for SQL objects

    Use naming conventions for example, v_name to represent a variable and c_name torepresent a constant variable.

    Assign a value ifNOTNULL constraint is use.

    Declare only one identifier per line (makes code easier to read and maintain).

    In constant declarations, the keyword CONSTANT must precede the type specifier.

    Example: v_sal CONSTANTREAL := 5000.00;

    Initialize the variable to an expression with the assignment operator (:=) or, equivalent,with the DEFAULT reserved word.

    Note: If you do not assign an initial value, the new variable contains NULL by defaultuntil you assign a value later.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    16/33

    IBM SOLUTIONS DELIVERY INC.

    16

    Naming Rules

    Two variables can have the same name, provided they are in different blocks.

    The variable name (identifier) should not be the same as the name of table columns usedin the block.

    Correct

    Example:

    Wrong

    DECLARE

    employee_id NUMBER(6);BEGIN

    SELECT employee_idINTO employee_idFROM employees

    WHERE last_name = Cruz;END;

    /

    DECLARE

    v_employee_id NUMBER(6);BEGIN

    SELECT employee_idINTO v_employee_idFROM employees

    WHERE last_name = Cruz;END;

    /

  • 8/8/2019 PLSQL Part1 Declaring Variables

    17/33

    IBM SOLUTIONS DELIVERY INC.

    17

    Variable Initialization and Keywords

    Assignment operator (:=)

    DEFAULT keyword

    NOTNULL constraint

    Syntax:

    identifier := expr;

    Examples:

    v_hiredate := 28-JAN-2008;

    v_lastname := Cruz;

  • 8/8/2019 PLSQL Part1 Declaring Variables

    18/33

    IBM SOLUTIONS DELIVERY INC.

    18

    Variable Initialization and Keywords

    In the Syntax:

    identifier is the name of the scalar variable.

    expr can be a variable, literal, or function callbut NOT a database column.

    Note:

    String literals must be enclosed in a single quotation marks.

    For example: Hello,world.

    If there is a single quotation mark in the string, use a single quotation mark twice.

    For example:

    the value is : FISHERMANS DRIVE

    the string would be: FISHERMANS DRIVE

  • 8/8/2019 PLSQL Part1 Declaring Variables

    19/33

    IBM SOLUTIONS DELIVERY INC.

    19

    Scalar Data Types

    A scalar data type holds a single value and has no internal components. Scalar datatypes can be classified into four categories:

    Number

    Character

    Date

    Boolean

    BASESCALAR DATA TYPES

    CHAR [(maximum_length)] VARCHAR2(maximum_length)

    LONG LONGRAW NUMBER [(precesion, scale)] BINARY_INTEGER

    PLS_INTEGER

    BOOLEAN

  • 8/8/2019 PLSQL Part1 Declaring Variables

    20/33

    IBM SOLUTIONS DELIVERY INC.

    20

    Base Scalar Data Types

    Data Type Description

    CHAR [(maximum_length)] Base type for fixed-length character data up to 32,767 bytes. If you do not specify amaximum_length, the default length is set to 1.

    VARCHAR2

    (maximum_length)

    Base type for variable-length character data up to 32, 767 bytes. There is no default size forVARCHAR2variables and constants.

    LONG Base type for variable-length character data up to 32, 760 bytes. Use LONG data type to

    store variable-length character strings. You can insert any LONG value into a LONGdatabase column because the maximum width ofLONG column is 2**31 bytes. However,you cannot retrieve a value longer than 32760 bytes for a LONG column into a LONG

    variable.

    LONGRAW Base type for binary data and byte strings up to 32, 760 bytes. LONGRAW is not interpreted

    by PL/SQL

    NUMBER [(precision,

    scale)]

    Number having precision p and scale s. The precision p can range from 1 to 38. The scale s

    can range from -84 to 127.

    BINARY_INTEGER Base type for integers between -2, 147, 483, 647 and 2,147, 483, 647.

    PLS_INTEGER Base type for signed integers between -2,147, 483,647 and 2,147, 2483, 647. PLS_INTEGER

    values require less storage and are faster than NUMBER and BINARY_INTEGER values.

    BOOLEAN Base type that stores one of three possible values used for logical calculations: TRUE,FALSE, or NULL

  • 8/8/2019 PLSQL Part1 Declaring Variables

    21/33

    IBM SOLUTIONS DELIVERY INC.

    21

    Base Scalar Data Types

    Data Type Description

    DATE Base type for dates and time. DATE values include the time of day in seconds since midnight.

    The range for date is between 4712 B.C. and 9999 A.D.

    TIMESTAMP The TIMESTAMP data type, which extends the DATE data type, stores the year, month, day,hour, minute, and second. The syntax is : TIMESTAMP [(precession)]where the

    optional parameter precision specifies the number of digits in the fractional of the secondsfield. You cannot use a symbolic constant or variable to specify the precision; you mustuse an integer literal in the range 0 .. 9. The default is 6.

    TIMESTAMP WITHTIME

    ZONE

    The TIMESTAMP WITHTIME ZONE data type, which extends the TIMESTAMP data type,

    includes a time-zone displacement. The time-zone displacement is the difference (in hoursand minutes) between local time and Coordinated Universal Time (UTC), formerly knownas Greanwich Mean Time. The syntax is: TIMESTAMP [(precision)]WITHTIMEZONE where the optional parameter precision specifies the number of digits in the

    fractional part of the seconds field. You cannot use a symbolic constant or variable tospecify the precision; you must use an integer literal in the range 0 .. 9. The default is 6.

    TIMESTAMP WITH LOCAL

    TIME ZONE

    The TIMESTAMP WITH LOCAL TIME ZONE data type, which extends TIMESTAMP data

    type, includes a time-zone displacement. The time-zone displacement is the difference (in

    hours and minutes) between local time and Coordinated Universal Time (UTC). Thesyntax is TIMESTAMP [(precision)]WITH LOCAL TIME ZONE where the optional

    parameter precision specifies the number of digits in the fractional part of the secondsfield. You cannot use the symbolic constant or variable specify the precision; you must use

    an integer or literal in the rang 0 .. 9. The default is 6.This data type differs from TIMESTAMP WITHTIME ZONE in that when you insert a value

    into a database column, the value is normalized to the database time zone, and the time-zone displacement is not stored in the column. When you retrieve the value, Oraclereturns the value in you local session time zone.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    22/33

    IBM SOLUTIONS DELIVERY INC.

    22

    Base Scalar Data Types

    INTERVAL YEARTOMONTH You use the INTERVAL YEARTOMONTH data type to store and manipulate intervals of

    years and months. The syntax is INTERVAL YEARTOMONTH [(precision)]TOMONTH where year_precision specifies the number of digits in the years field. You cannot

    use a symbolic constant or variable to specify the precision; you must use an integer literal inthe range 0 .. 4. The default is 2..

    INTERVAL DAYTO SECOND You use the INTERVAL DAYTO SECOND data type to store and manipulate intervals ofdays, hours, minutes, and seconds. The syntax is : INTERVAL DAY [(precision1)]TOSECOND [(precision2)]where precesion1 and precision2 specify the number of digits

    in the days field and seconds field, respectively. In both cases, you cannot use a symbolicconstant or variable to specify the precision; you must use an integer literal in the range 0 .. 9.

    The defaults are 2 and 6, respectively.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    23/33

    IBM SOLUTIONS DELIVERY INC.

    23

    The %TYPE Attribute

    When declaring PL/SQL variables, the developer must ensure the variable is of the correctdata type and precision. If not, PL/SQL error will occur during execution.

    Rather than hard coding the data type and precision of a variable, the developer can usethe %TYPE attribute to declare a variable according to another previously declared variableor database column.

    The %TYPE attribute is most often used when the value stored in the variable will bederived from a table in the database.

    Syntax:

    identifier Table.column_name%TYPE

    Examples:

    ...v_name employees.last_name%TYPE;v_salary NUMBER(7,2);

    ...

  • 8/8/2019 PLSQL Part1 Declaring Variables

    24/33

    IBM SOLUTIONS DELIVERY INC.

    24

    Declaring Boolean Variables

    Only the values TRUE, F

    ALSE, and NULL can be assigned to a Boolean variable.

    The variables are compared by the logical operators AND, OR, and NOT.

    The variables always yield TRU, FALSE, or NULL.

    Arithmetic, character, and date expression can be use to return a Boolean value.

    Examples:

    v_sal1 := 3000;v_sal2 := 4000;

    The expression yields to TRUE.

    v_sal1 < v_sal2.

    Declare and initialize a Boolean variable

    DECLARE

    v_flag BOOLEAN := FALSE;BEGIN

    v_flag := TRUE;END;

  • 8/8/2019 PLSQL Part1 Declaring Variables

    25/33

    IBM SOLUTIONS DELIVERY INC.

    25

    LOB Data Type Variables

    LOB (large object) data type, can store block of unstructured data (such as text, graphicimages, video clips, and sound wave forms) up to 4 gigabytes in size. LOB data typesallow efficient, random, piecewise access to the data and can be attributes of an objecttype. LOBs also support random access to data.

    CLOB (character large object) data type is used to store large blocks of

    single-byte character data in the database in line (inside the row) or out ofline (outside the row). (i.e. BOOK)

    BLOB (binary large object) data type is use to store large binary objects inthe database in line (inside the row) or out of line (outside the row). (i.e.PHOTO)

    BFILE (binary file) data type is used to store large binary objects inoperating system files outside the database. (i.e. MOVIE)

    NCLOB (national language character large object) data type is used tostore large blocks of single-byte or fixed-width multibyte NCHAR unicodedata in the database, in line or out of line.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    26/33

    IBM SOLUTIONS DELIVERY INC.

    26

    BIND Variables

    A bind variable is a variable that you can declare in a host environment. Bind variables canbe used to pass run-time values, either number or character, into or out of one or morePL/SQL programs.

    Creating Bind Variables

    To declare a bind variable in the iSQL*Plus environment, use the command VARIABLE.

    For example:

    Developer declare a variable type ofNUMBERorVARCHAR2 as follows:

    VARIABLE return_code NUMBERVARIABLE return_msgVARCHAR2(3)

  • 8/8/2019 PLSQL Part1 Declaring Variables

    27/33

    IBM SOLUTIONS DELIVERY INC.

    27

    Using Bind Variables

    To reference a bind variable in PL/SQL, you must prefix its name with a colon (:).

    Example:

    VARIABLE g_salary NUMBER

    BEGINSELECT salaryINTO :g_salaryFROM employees

    WHERE employee_id = 180;END;/PRINT g_salary

  • 8/8/2019 PLSQL Part1 Declaring Variables

    28/33

    IBM SOLUTIONS DELIVERY INC.

    28

    Referencing Non-PL/SQL Variables

    To reference host variables, you must prefix the references with a colon (:) to distinguishthem from declared PL/SQL variables.

    Example:

    SET VERIFY OFF

    VARIABLE g_monthly_sal NUMBERDEFINE p_annual_sal = 5000

    DECLAREv_sal NUMBER(9,2) := &p_annual_sal;

    BEGIN:g_monthly_sal := v_sal/12;

    END;

    /PRINT g_monthly_sal

    Note: The DEFINE command specifies a user variable and assigns it a CHARvalue.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    29/33

    IBM SOLUTIONS DELIVERY INC.

    29

    DBMS_OUTPUT.PUT_LINE

    You have seen that you can declare a host variable, reference it in a PL/SQL block, andthen display its contents in iSQL*Plus using the PRINT command.

    Another option for displaying information from a PL/SQL block is DBMS_OUTPUT.PUTLINE.

    An Oracle-supplied packaged procedure

    An alternative for displaying data from a PL/SQL block

    Must be enabled in iSQL*Plus with SET SERVEROUTPUT ON.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    30/33

    IBM SOLUTIONS DELIVERY INC.

    30

    DBMS_OUTPUT.PUT_LINE

    Example:

    SET SERVEROUTPUT ONDEFINE p_annual_sal = 60000DECLARE

    v_sal NUMBER(9,2) := &pa_annual_sal;

    BEGINv_sal := v_sal/12;DBMS_OUTPUT.PUT_LINE (Themonthlysalary is ||

    TO_CHAR(v_sal));END;/

    The output is:

    The monthly salary is 5000PL/SQL procedure successfully completed.

  • 8/8/2019 PLSQL Part1 Declaring Variables

    31/33

    IBM SOLUTIONS DELIVERY INC.

    31

    Questions?Questions?

  • 8/8/2019 PLSQL Part1 Declaring Variables

    32/33

    IBM SOLUTIONS DELIVERY INC.

    32

    Practice ExercisePractice Exercise

  • 8/8/2019 PLSQL Part1 Declaring Variables

    33/33

    IBM SOLUTIONS DELIVERY INC.

    33