Learning PLSQL

download Learning PLSQL

of 10

Transcript of Learning PLSQL

  • 7/28/2019 Learning PLSQL

    1/10

    Learning PL/SQL

    Variables are used in all programming languages to store and manipulate data.

    In PL/SQL, yu can use variables to store information from a database table and then performcalculations on it.

    Variables provide:

    1. ReusabilityVariables can be reused. You can refer to a variable in executable section as often you need.

    2. Temporary storageYou must first declare a variable in declaration section of your PL/SQL code. When youdeclare a variable, a temporary storage area is allocated in memory. You use this memoryarea to store data temporarily.

    3. The ability to manipulate dataOnce you have declared a variable, you can manipulate the value of the data it holds in the

    execution section of your PL/SQL code.

    Identifiers are used to name PL/SQL objects such as variables, types, cursors, and subprograms.

    A variable is essentially a data storage location.An identifier is used to name and reference a variable.

    Variable identifier must start with a letter.Variables can include numbers, letters and special characters such as $, _, and pound sign.PL/SQL variables are not case-sensitivePL/SQL variables can not be longer than 30 characters.You can not use PL/SQL reserved words.

    You must assign a data type to every variable you declare. The data type is used to specify: thestorage format of the data and any constraints that are to be placed on a variable's value.

    Data type specifies the range of valid values a variable can hold.

    PL/SQL has five data type categories:

    1. bind

    Some times called host variables. Bind variables are non-PL/SQL variables in the sense thatthey are created in the host environment. They are declared outside a PL/SQL block andthey can be used by multiple PL/SQL subprograms.

    2. CompositeComposite types can hold both single and multiple values, such as entire database record.Some what similar to structs in C.

    3. large object (LOB)LOB data type is used to store a large amount of information, such as database column. Thistype is generally useful for referring to large files, such as movie file, that exist outside the

    database.

  • 7/28/2019 Learning PLSQL

    2/10

    4. ReferenceReference data types to store pointers, which point to storage locations. You might use a

    pointer to point to a particular row in a table.

    5. Scalar Scalar data types hold a single value only, such as a string or a number. The value of a scalar

    variable depends on its data type.Like, VARCHAR2, NUMBER, BOOLEAN, etc.

    You must declare all variables, apart from bind variables, in the declarative section of PL/SQL codebefore you can reference it in the executable section.

    It is good practice to initialize a variable by assigning it a value in the declarative section. However,you can assign or change a variable's value in the executable section.

    You can also use variables as parameters in subprograms or to hold values returned by functions.

    Syntax used to declare a variable:

    CONSTANT NOT NULL :=| DEFAULT expr

    clause is mandatory and it should be unique.Ex: manager_id VARCHAR2;

    CONSTANT clause is optional. You must initialize variables declared with CONSTANT clause inthe declarative section, not in the executable section.Ex: c_comm CONSTANT NUMBER := 1400;

    is mandatory. You must specify a data type when declaring a variable. It can be ascalar, composite, reference or LOB data type.Ex: location VARCHAR2;

    NOT NULL clause is optional. This is to ensure that a variable cannot contain a NULL value. Youmust initialize variables declared with the NOT NULL clause in the declarative section.Ex: emp_deptno NUMBER(2) NOT NULL := 10;

    :=| DEFAULT expr

    It is good practice to initialize a variable in the declarative section. You use the := assignmentoperator to assign a variable to the value specified in expr.You can alternatively use the DEFAULT statement to assign a default value to the variable. You canchange a variable's default or initial value in the executable section.Ex: location VARCHAR2 DEFAULT 'Atlanta'

    String literals in PL/SQL must be enclosed by single quotes.Ex: my_name VARCHAR2(20) := 'John';

    You use the DBMS_OUTPUT.PUT_LINE command to output a value.

    Ex:DBMS_OUTPUT.PUT_LINE('My name is: ' || my_name);

  • 7/28/2019 Learning PLSQL

    3/10

    Guidelines when declaring and initializing variables:

    Delimit string literals:If you want to use a single quote in a string literal, you must include an extra quotation mark as anescape character.

    Alternatively, you can use the q notation.

    Ex:event1 VARCHAR2(20) := 'Father''s day';event2 VARCHAR2(20) := q'%Father's day%';

    You should avoid naming a variable after a table column. When you reference a variable with atable column name in SQL, the Oracle Server assumes you are referencing the column rather thanthe variable, which can result in errors.

    Four categories of scalar data type:

    a. Characterb. Datec. Numberd. Boolean

    Text and Number data types:

    BINARY_INTEGER : similar to signed int in C. ( 4byte signed int)Calculations performed on BINARY_INTEGER variables are faster than on NUMBER variables,although it is not as efficient as the PLS_INTEGER type.Ex: count_loop BINARY_INTEGER := 0;

    CHAR : 2 byte char. Used to hold fixed-length character data. However it is recommended to useVARCHAR2 data type to hold character data.You can specify a maximum length, or accept the default of 1 character.Syntax: CHAR[(max_length)]Ex: dept_name CHAR(8) := 'Accounts';

    NUMBER: data type to hold interger, fixed or floating-point numeric values.

    You can specify precision, which is the number of significant digits the variable can hold, and scale,which is the number of digits to the left or right of the decimal point.Syntax: NUMBER[(precision, scale)]Ex: c_tax_rate CONSTANT NUMBER(3, 2) : = 8.25;

    PLS_INTEGER : signed integer values between -2^31 and 2^31. Variables of this data type requiresless storage than NUMBER and BINARY_INTEGER variables.Calculations performed on them are also faster.Ex: count_loop PLS_INTEGER := 0;

    VARCHAR2(max_length) : data type to hold variable length character data. There is no defaultmaximum character length. You must specify the length manually.Ex: dept_name VARCHAR2(9) := 'Accounts';

  • 7/28/2019 Learning PLSQL

    4/10

    Oracle Database 10g includes two data types to represent floating point numbers.

    BINARY_DOUBLE 9bytes. Literals of this type end with d, like 140d.

    BINARY_FLOAT 5bytes. Literals of this type end with f, like 35f.

    Use these data types to perform scientific calculations.

    Date and Time data types:

    DATE: data type to hold 7-byte fixed length date time value.DATE variables hold, year, month, day, hour, minute and second information.Ex: orderdate DATE := SYSDATE + 7;

    SYSDATE is a PL/SQL function.

    TIMESTAMP : data type is an extension of the DATE data type. It also includes fractions of asecond. You have the option to specify the number of digits in the fractional section, or accept thedefault of 6.Ex: orderdate TIMESTAMP(5) := SYSDATE + 7;

    TIMESTAMP WITH LOCAL TIME ZONE : data type is an extension of the TIMESTAMP datatype. Regards the date time as belonging to the local time zone.In PL/SQL, the local time zone is the same as the session time zone.

    TIMESTAMP WITH TIME ZONE : extension of the TIMESTAMP data type. It includes thedifference in hours and minutes between local time and UTC time.Ex: orderdate TIMESTAMP WITH TIME ZONE := SYSDATE + 7;

    BOOLEAN type: typically used in logical calculations.Three possible values: TRUE, FALSE, or NULL.

    NULL value represents an inapplicable or unknown value.Ex: valid BOOLEAN NOT NULL := TRUE;

    What if the data type and precison of a table column do not match the data type of a variableholding a value from the column????

    Solution: Rather than explicitly declaring a variable's data type, you can use %TYPE attribute toanchor the variable's data type so that it matches that of a table column.This avoids errors caused by mismatching data types, and additionally allows you to change tablecolumn definitions without having to update your code.

    The %TYPE attribute also overrides the NOT NULL constraint in the table columns. Even if thesource column includes the constraint, the variable can still contain the NULL value.

    You can also use the %TYPE attribute to anchor a variable's data type to a variable previouslydeclared in the same code block, or to a global variable.

  • 7/28/2019 Learning PLSQL

    5/10

    Syntax: %TYPE;

    First, name the variable using a unique identifier. Then instead of explicitly stating a data type, youspecify the source table and column name, or alternatively the name of a previously declared

    variable. Finally, you append the %TYPE attribute.

    Ex:emp_lname employess.last_name%TYPE; - the variable's type is inherited from the last_namecolumn in the employees table.

    balance NUMBER(7,2);min_balance balance%TYPE := 1000;

    You use Boolean variables with the operators AND, OR, and NOT to test validity of an expression.

    DBMS_RANDOM.VALUE() - this function returns a randomly generated number between zeroand one.

    := --> assignment operator= --> equality test operator

    Small Example:

    DECLARErand NUMBER;result BOOLEAN;

    BEGINrand := DBMS_RANDOM.VALUE();

    IF rand > 0.5 THENresult := true;ELSEresult := false;

    END IF;

    IF result = true THENDBMS_OUTPUT.PUT_LINE('The result was true');ELSEDBMS_OUTPUT.PUT_LINE('The result was false');END IF;END;

  • 7/28/2019 Learning PLSQL

    6/10

    Bind Variables:

    Declared outside PL/SQL block. Typically, they are created in host environment and are also calledhost variables.

    Can be used in multiple PL/SQL programs.

    Any variables scalar variables declared in PL/SQL block are avaiable only when you executethe block. When block executes, the memory used by the variable is freed. However, bind variablesare accessible even after the block is executed.

    These variables can be passed as runtime values into or out of PL/SQL subprograms. Can be usedand manipulated by multiple subprograms used in SQL statement and PL/SQL blocks.

    Syntax:VARIABLE

    Ex:VARIABLE emp_salary NUMBER;

    To create a bind variable, you use the VARIABLE command.Bind variables must have an identifier.The data type of the bind variable must be specified.

    Bind variables are referenced by preceding the variable name with a colon. Bind variable can beused in any SQL statement or PL/SQL program.

    Ex:VARIABLE emp_salary NUMBER

    BEGINSELECT salary INTO :emp_salary FROM employees WHERE employee_id = 120;

    END;

    PRINT emp_salary

    DEFINE : command can be used to create a user variable. It specifies teh value of a user variable.Variables should be CHAR type only. These user variables can be used many times in the samePL/SQL block.

    These user variables can be referenced same way as substituion variables, like preceding & with thevariable.

  • 7/28/2019 Learning PLSQL

    7/10

    Control Statements:

    Conditional control enables you to control the execution of statements in a block of PL/SQL code.

    You can direct the control of execution through your program using IF and CASE statements.

    IF statements enable you to perform actions selectively, based on specified conditions.

    3 distinctive IF logic structures:

    1. IF THEN END IF;2. IF THEN ELSE END IF;3. IF THEN ELSIF ELSE END IF;

    You can use an IF THEN statement to test a particular condition.

    In the syntax of a standard IF THEN statement, the condition is a Boolean variable or expressionthat results in TRUE, FALSE or NULL.

    IF THEN....executable statements....END IF;

    IF THEN ELSE is based on either/or logic, one of the statements will always be executed. You canonly have one ELSE keyword in an IF statement.

    IF condition1THEN

    statements1ELSIF conditionNTHEN

    statementsN[ELSE

    else statements]END IF;

  • 7/28/2019 Learning PLSQL

    8/10

    CASE control structures

    Alternative to IF ELSIF statement. More compact way of writing code to check for multipleconditions.

    2 types of CASE controls:

    CASE statement : evaluates a condition and performs an action. Like, switch.End with END CASE;

    2 types of CASE statements:

    Simple CASE statement : Associates PL/SQL statements with a value. It chooses which sequence ofstatements to be executed based on expression that returns one of those values.

    CASE employee_dept

    WHEN 'W' THENaward_salary_bonus(employee_id);WHEN 'M' THENaward_montly_bonus(employee_id);ELSERAISE invalid_employee_type;END CASE;

    Searched CASE statement : evaluating a list of Boolean conditions. The statement associated withthe first condition that results in TRUE is executed.

    CASEWHEN salary >= 10000 AND salary 20000 AND salary

  • 7/28/2019 Learning PLSQL

    9/10

    Searched CASE expression

    Simple CASE statements enable you to choose which of several sequences of stmts to execute

    based on results of an expression/selector.

    Simple CASE expression selects a result and returns it. Simple CASE expressions compare onlyone value and cannot contain any comparison operators.

    Searched CASE controls work using comparisons. The WHEN clause is used to perform thecomparisons.

    Searched CASE statements do not have a selector defined. It evaluates a list of Booleanexpressions. Always specify the ELSE part explicitly when you use a searched CASE statement.

    Searched CASE expression does not use a selector. Nor does the searched CASE expression have atest expression. Instead, the WHEN clause contains an expressin that returns a Boolean value.

    Loops in PL/SQL

    three main types:

    1. basic loops like do while loop. Execute at least once.LOOP

    statement1....EXIT [WHEN condition]

    END LOOP;

    2. WHILE loop loop based on condition.WHILE condition LOOP

    statement1;statement2;.....

    END LOOP;

    3. FOR loops loops based on a count. You must specify a range of numbers that a countervalue must step through.

  • 7/28/2019 Learning PLSQL

    10/10

    Writing FOR loops in PL/SQL:

    If you have one or more statements you want to execute repeatedly for a set number of iterations,you can use a FOR loop.

    Syntax:

    FOR IN .. LOOPstatement1;statement2;.....END LOOP;

    lower bound and upper bound are included in the loop range. Lower bound must always be lowerthan the upper bound.

    Ex:

    FOR i IN 3..6 LOOPstatement1;END LOOP;

    In the above, the counter variable i, doesn't need to be declared earliers, as it is declared implicitly.Counter variable should only be referenced within the loop, it is undefined outside the loop.

    When specifying a label for a loop, the name must be included in label delimiters, like below:,

    If you have labeled your loop, you can optionally include the label names after the END LOOP;statements.