66
Handout: Oracle 10g PL/SQL Version: ORACLE10gPLSQL/Handout/0308/1.0 Date: 31-03-08 Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com

Handout Oracle 10g PLSQL v1.0

Embed Size (px)

Citation preview

Page 1: Handout Oracle 10g PLSQL v1.0

Handout: Oracle 10g PL/SQL Version: ORACLE10gPLSQL/Handout/0308/1.0

Date: 31-03-08

Cognizant

500 Glen Pointe Center West

Teaneck, NJ 07666

Ph: 201-801-0233

www.cognizant.com

Page 2: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

TABLE OF CONTENTS

Introduction ................................................................................................................................... 5 

About this Module ......................................................................................................................... 5 

Target Audience ........................................................................................................................... 5 

Module Objectives ........................................................................................................................ 5 

Pre-requisite ................................................................................................................................. 5 

Session 02: PL/SQL Fundamentals .............................................................................................. 6 

Learning Objectives ...................................................................................................................... 6 

PL/SQL Features .......................................................................................................................... 6 

PL/SQL Architecture ..................................................................................................................... 6 

PL/SQL Block Structure ................................................................................................................ 8 

Identifiers ...................................................................................................................................... 9 

Variables ....................................................................................................................................... 9 

Data Types ................................................................................................................................. 11 

PL/SQL Statements .................................................................................................................... 12 

Expressions and Operators ........................................................................................................ 12 

Conditional and Loop Constructs ............................................................................................... 13 

Summary .................................................................................................................................... 16 

Test Your Understanding ............................................................................................................ 16 

Session 05: PL/SQL Subprograms ............................................................................................. 17 

Learning Objectives .................................................................................................................... 17 

Understand Subprograms .......................................................................................................... 17 

Procedures ................................................................................................................................. 18 

Functions .................................................................................................................................... 20 

Procedure VS Function .............................................................................................................. 23 

Packages .................................................................................................................................... 23 

Oracle Supplied Packages ......................................................................................................... 25 

Summary .................................................................................................................................... 26 

Test Your Understanding ............................................................................................................ 26 

Session 07: Triggers .................................................................................................................... 27 

Learning Objectives .................................................................................................................... 27 

Appreciate Database Triggers .................................................................................................... 27 

Components of Triggers ............................................................................................................. 27 

Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 3: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Types of Triggers ........................................................................................................................ 28 

Create Triggers ........................................................................................................................... 28 

Order of Trigger Firing ................................................................................................................ 32 

Summary .................................................................................................................................... 32 

Test Your Understanding ............................................................................................................ 32 

Session 10: Cursors and Exceptions ......................................................................................... 33 

Learning Objectives .................................................................................................................... 33 

Understand Cursors ................................................................................................................... 33 

Fetch Cursor ............................................................................................................................... 35 

Close Cursor ............................................................................................................................... 35 

Cursors FOR LOOP ................................................................................................................... 40 

The For Update Clause .............................................................................................................. 40 

The WHERE CURRENT OF Clause .......................................................................................... 41 

Understanding Exceptions .......................................................................................................... 41 

Predefined Exceptions ................................................................................................................ 42 

User Defined Exception .............................................................................................................. 43 

PRAGMA EXCEPTION_INIT ..................................................................................................... 44 

RAISE_APPLICATION_ERROR ................................................................................................ 45 

Summary .................................................................................................................................... 46 

Test Your Understanding ............................................................................................................ 46 

Session 12: PL/SQL Collection, Record, and Varrays .............................................................. 47 

Objectives ................................................................................................................................... 47 

Introduction ................................................................................................................................. 47 

Collection .................................................................................................................................... 47 

Index-by tables ........................................................................................................................... 47 

Nested Table .............................................................................................................................. 49 

Varrays ....................................................................................................................................... 50 

Collection method ....................................................................................................................... 50 

Summary .................................................................................................................................... 51 

Test Your Understanding ............................................................................................................ 51 

Session 14: Dynamic SQL ........................................................................................................... 52 

Learning Objectives .................................................................................................................... 52 

Understand Dynamic SQL .......................................................................................................... 52 

Use of Dynamic SQL .................................................................................................................. 52 

Execute Dynamic SQL ............................................................................................................... 53 

Page 3 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 4: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Understand Bulk Operations ...................................................................................................... 54 

Understand FOR ALL ................................................................................................................. 55 

Understand BULK COLLECT ..................................................................................................... 56 

Appreciate the difference between Soft Parse and Hard Parse ................................................. 56 

Summary .................................................................................................................................... 56 

Test Your Understanding ............................................................................................................ 57 

Session 17: Oracle Utilities ......................................................................................................... 58 

Objectives ................................................................................................................................... 58 

Introduction ................................................................................................................................. 58 

Export and Import Utility: Overview ............................................................................................ 58 

Oracle EXPORT utility ................................................................................................................ 58 

Oracle Import utility ..................................................................................................................... 60 

Oracle SQL *Loader utility .......................................................................................................... 62 

Summary .................................................................................................................................... 63 

Test Your Understanding ............................................................................................................ 64 

References .................................................................................................................................... 65 

Websites ..................................................................................................................................... 65 

Books .......................................................................................................................................... 65 

STUDENT NOTES: ........................................................................................................................ 66 

Page 4 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 5: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Introduction

About this Module

The module provides an overview about the basics of PL/SQL statements in Oracle.

Target Audience

This module is designed for the entry level trainees.

Module Objectives

After completing module, you will be able to: Write PL/SQL statements Write Static and Dynamic SQL statements Create procedures, functions, packages, and triggers Use static and dynamic cursors in PL/SQL blocks

Pre-requisite

The trainees need to have an idea of the following: General Programming and Logic Structured Query Language Relational DBMS

Page 5 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 6: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 02: PL/SQL Fundamentals

Learning Objectives

After completing this session, you will be able to: Write PL/SQL Statements

PL/SQL Features

PL/SQL stands for Procedural Language/SQL PL/SQL extends SQL by adding constructs found in other procedural languages

Variables and types Control Structures (IF-THEN-ELSE) Procedures and Functions Object types and methods

Need of PL/SQL

Procedural Language/Structured Query Language is an extension to SQL PL/SQL provides programming facility to the users Set of instructions that can be stored in the server as Database Objects in compiled form

PL/SQL Architecture

How PL/SQL Works Blocks of PL/SQL statements are translated by the PL/SQL engine that can reside either

in the client or at the server side. It divides the SQL statements from PL/SQL block and sends them to SQL STATEMENT EXECUTOR.

The output finally comes to the client end.

Page 6 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 7: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Figure 1.1 - PL/SQL engine at client side

Figure 1.2 - PL/SQL engine at server side

Page 7 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 8: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

PL/SQL Block Structure

PL/SQL is a block-structured language. PL/SQL program is made up of a series of statements. A statement is terminated with a

semicolon (;), not with the physical end of a line. It has three parts, declarative part, an executable part and an exception handling part.

Syntax is as follows: DECLARE

/*Declarative Section - PL/SQL variables,

cursors and types */

BEGIN

/* Executable section - procedural and SQL statements */

EXCEPTION

/* Exception handling section - error handling statements */

END;

Anonymous Blocks

Declare

/* variables*/

Begin

/*SQL statements */

Exception

/* Error handling */

End;

Section Description Inclusion

Declarative Contains all variables, constants, cursors and user defined 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

Page 8 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 9: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Anonymous Blocks: Anonymous Blocks are unnamed blocks. Declare

/* variables*/

Begin

/*SQL statements */

Exception

/* Error handling */

End;

Named Block

Replace DECLARE keyword with CREATE OR REPLACE

Example

Create or Replace Procedure Validate_Date AS

/* variables*/

Begin

/*SQL statements */

Exception

/* Error handling */

End Validate_Date;

Identifiers

Can contain up to 30 characters. Must begin with an alphabetic character. Can contain numerals, underscores, dollar sign, and number signs. Can not contain characters such as hyphens, slashes, and spaces. Should not have the same name as a database table column name. Should not be reserved words.

You can use the Identifiers to do the followings:

Declare variables, constants, cursors and exceptions and then use them in SQL and procedural statements.

Declare variables belong to scalar, reference, composite and large object (LOB) data types.

Declare variables dynamically based on the data structure of tables and columns in the database.

Variables

Variables are memory locations, which can store data values Information from database can be assigned to a variable, or the contents of a variable can

be inserted into the database The variables are declared in the declarative section of the block Every variable has a specific type which describes what kind of information it can store

Page 9 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 10: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Variable Declarations Declaration Syntax

variable_name type [CONSTANT][NOT NULL][:=value]

Example

DECLARE

v_Description VARCHAR2(50);

v_NumberSeats NUMBER := 45;

v_Counter BINARY_INTEGER DEFAULT 0;

Declare and initialize variables in the declaration sections. Assign new value to variable in the executable section. Pass values into PL/SQL blocks through parameters. View result through output variables.

Type of variables:

PL/SQL variables: Scalar Composite Reference LOB (large objects)

Non PL/SQL variables:

Bind Host

Bind Variables: A bind variable is a variable that you declare in a host environment. Bind variables can be used to pass run time values either number or character, into or out of one or more PL/SQL program. Declare the variable in SQL * PLUS environment by VARIABLE key word. VARIABLE return_code number

HOST Variables: You can access HOST variables in PL/SQL program. VARIABLE result number These variable should proceeded by a colon. : Result

Page 10 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 11: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Data Types

Scalar data types hold a single value. Composite data types allow group of fields to be defined and manipulated in PL/SQL

blocks. Reference data types hold values that designate other program item. LOB (large objects) data types hold values, called locators that specify the location of the

large object (such as graphic images) that are stored out of line. Base Scalar data types are as follows:

CHAR [(maximum_length)]

VARCHAR2(maximum_length)

LONG

LONG RAW

NUMBER[(precision , scale)]

BINARY_INTEGER

PLS_INTEGER

BOOLEAN

DATE

TIMESTAMP

TIMESTAMP WITH TIME ZONE

TIMESTAMP WITH LOCAL TIME ZONE

INTERVAL YEAR TO MONTH

INTERVAL DAY TO SECOND

Composite data types: Composite data types also known as collections are of following types

TABLE

RECORD

NESTED TABLE

VARRAYS

LOB data types: With the LOB data types you can store blocks of unstructured data (such as text, graphic images, video clips) up to 4GB.

CLOB: The 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 line (outside the row).

BLOB: The BLOB (binary large object) data type is used to store binary large objects data in the database in line (inside the row) or out line (outside the row).

BFILE: The BFILE (binary file) data type is used to store large binary objects in operating system files outside the database.

NCLOB: The (National Character Large Object) data type is used to store large blocks of single byte or fixed width multi-byte NCHAR Unicode data in the database in line (inside the row ) or out line (outside the row) .

Page 11 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 12: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

PL/SQL Statements

Statements in PL/SQL The INTO clause must be used to store a table column value into a variable declared in

the DECLARATION section of PL/SQL block

SELECT ENAME INTO MEMNAME FROM EMP WHERE EMPNO=101176;

Multiple column values can be assigned to equal number of memory variables using single INTO

SELECT ENAME, SAL INTO MEMNAME, MEMSAL FROM EMP WHERE EMPNO=101176;

Expressions and Operators

Operator: An operator is used to manipulate individual data items and return a result. These items are called operands or arguments. Operators are represented by special characters or by keywords. For example, the multiplication operator is represented by an asterisk (*) and the operator that tests for nulls is represented by the keywords IS NULL. The main SQL operators are described below: Unary and Binary Operators: A unary operator operates on only one operand. A unary operator typically appears with its operand in this format: operator operand A binary operator operates on two operands. A binary operator appears with its operands in this format: operand1 operator operand2 Precedence: An important property of an operator is its precedence. Precedence is the order in which Oracle evaluates different operators in the same expression. When evaluating an expression containing multiple operators, Oracle evaluates operators with higher precedence before evaluating those with lower precedence. Oracle evaluates operators with equal precedence from left to right within an expression. Arithmetic Operators: You can use an arithmetic operator in an expression to negate, add, subtract, multiply, and divide numeric values. The result of the operation is also a numeric value. Some of these operators are also used in date arithmetic. Some examples of arithmetic operators are: +, -, *, / and so on.

Page 12 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 13: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Character Operators: Character operators are used in expressions to manipulate character strings. Following is an example of a character operator:

Operator Purpose Example

II Concatenates Character Strings SELECT ‘Name is’ II ename FROM emp

Comparison Operators: Comparison operators are used in conditions that compare one expression to another. The result of comparing one expression to another can be TRUE, FALSE, or UNKNOWN. Below is given an example of a comparison Operator:

Operator Purpose Example

+ Equality Test SELECT * FROM emp WHERE sal=1500

Logical Operators: A logical operator combines the results of two component conditions to produce a single result based on them or to invert the result of a single condition. The main comparison operators are: AND, Not and OR Below is given an example of a comparison Operator:

Operator Function Example

NOT

Returns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE. If it is UNKNOWN, it remains UNKNOWN

SELECT * FROM emp WHERE NOT (sal BETWEEN 1000 AND 2000)

Set Operators: Set operators combine the results of two component queries into a single result. Queries containing set operators are called compound queries. The main set operators are: UNION, UNION ALL, INTERSECT and MINUS Expression: An expression is a sequence of variables and literals, separated by operators. The most basic operator is assignment. Syntax Variable: = expression

Variable is PL/SQL variable and expression is PL/SQL expression PL/SQL expression is: 3 + 5 * 7 Concatenation operator (||) attaches two or more strings together. For example, the expression ‘Hello ’||’World’ evaluates to ‘Hello World’.

Conditional and Loop Constructs

You can change the logical flow of statements within the PL/SQL block with the following control structures.

IF-THEN-ELSE

LOOPS

WHILE LOOPS

FOR LOOPS

Page 13 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 14: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

IF-THEN-ELSE Syntax IF boolean_statements1 THEN

sequence_of_statements1;

ELSIF boolean_statements2 THEN

sequence_of_statements2;

ELSE

sequence_of_statements3;

END IF;

There are three conditional structures: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF-THEN-...-ELSE. The IF-THEN format executes a code block if the condition is TRUE. For example: IF line_count > LINES_PER_PAGE

THEN

line_count: = 0;

DBMS_SQL.PUT_LINE ('--------');

END IF;

The IF-THEN-ELSE format has two code blocks. If the condition is TRUE, the first block is executed; otherwise, the second block is executed. For example: IF items_sold > get_employee_target (emp_id)

THEN

over_quota_count: = over_quota_count + 1;

give_raise (emp_id);

ELSE

give_talking_to (emp_id);

END IF;

The IF-THEN-ELSIF-THEN-...-ELSE, PL/SQL's equivalent of the CASE or SWITCH statement, can contain multiple conditions. The statement executes the code block associated with the first TRUE condition. Here's an example: IF is_number (current_char)

OR is_letter (current_char)

THEN

new_char: = current_char;

ELSIF current_char = ' '

THEN

new_char: = '+';

ELSE

new_char := convert_to_hex (current_char);

END IF;

Page 14 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 15: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Loops: Looping, or iteration, causes the block between the keywords LOOP and END LOOP to be repeatedly executed. The loop ends, or terminates, when an exit condition is met. Once a loop terminates, program control is returned to the first line after the END LOOP keyword. There are three looping structures: simple, WHILE, and FOR. In the simple loop, the exit condition is embedded inside the loop body. The EXIT command terminates the loop immediately, and is usually embedded inside an IF...THEN statement. EXIT WHEN combines EXIT with a conditional to form a more compact syntax. Here are two constructions of a simple loop. The first example uses EXIT: LOOP

COUNT: = COUNT + 1;

IF COUNT > 10

THEN

EXIT;

END IF;

END LOOP;

The second example uses EXIT WHEN: LOOP

COUNT: = COUNT + 1;

EXIT WHEN COUNT > 10;

END LOOP;

In the second kind of loop, the WHILE loop, the exit condition is outside the body of the loop. The code within the body of the loop iterates while the loop condition is true. The loop terminates when the condition is false, for example: WHILE (COUNT <= 10)

LOOP

COUNT: = COUNT + 1;

END LOOP;

The last kind of loop, the FOR loop, iterates a predetermined number of times. For example, the number of loops needed to process each month in the year does not depend on a complex condition; it always requires 12 passes through the loop. A FOR loop is controlled by an index variable that ranges from a lower bound to an upper bound. The index variable begins at the lower bound. Each passes through the loop increments it. The loop terminates when the index reaches the upper bound, for example: FOR month_index IN 1.. 12

LOOP

process_month_sales (month_index);

END LOOP;

Page 15 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 16: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Summary

A PL/SQL block can be anonymous block or named block. Variables are memory locations, which can store data values Variables declare in external environment are called host variable. Scalar data types hold a single value. Composite data types allow group of fields to be defined and manipulated in PL/SQL

blocks. An expression is a sequence of variables and literals, separated by operators. You can change the logical flow of statements within the PL/SQL block with the following

control structures. o IF-THEN-ELSE

o LOOPS

o WHILE LOOPS

o FOR LOOPS

Test Your Understanding

1. What is difference between SQL and PL/SQL? 2. What is an anonymous PL/SQL block? 3. What are the different Scalar data types? 4. What are the different composite data types? 5. What are the different LOB data types? 6. What is a bind variable? 7. What is a host variable? 8. What is the use of identifiers? 9. What are the different sections in a PL/SQL blocks and which of them are mandatory and

which are optional? 10. What is a named PL/SQL blocks? 11. What is an expression? 12. What are the different types of operators? 13. What is an exponentiation operator? 14. What are the different types of loop structures? 15. Explains each loops structure?

Page 16 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 17: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 05: PL/SQL Subprograms

Learning Objectives

After completing this session, you will be able to: Write Procedures Write Functions Write Packages

Understand Subprograms

Is a named PL/SQL block that can accept parameters and be invoked from a calling environment

Is of two type: A procedure that performs an action A function that computes a value. Is based on standard PL/SQL block structure. Provides modularity, reusability, extensibility and maintainability.

Block structure for PL/SQL subprograms

The header is relevant for named blocks only and determines the way that the program unit is called or invoked. The header determines:

The PL/SQL subprogram type, that is, either a procedure or a function The name of the subprogram The parameter list, if one exists The RETURN clause, which applies only to functions

The IS or AS keyword is mandatory.

Page 17 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 18: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Benefits of Subprograms Easy maintenance Improved data security and integrity Improved performance Improved code clarity

Procedures

What is a Procedure? It is a sub program in the PL/SQL block, which can perform a specific task when invoked explicitly with or without parameter. A Procedure has two parts: Specification and Body Specification: This section begins with the keyword Procedure followed by its name and Parameter list (optional) Body: Procedure Body begins with the keyword IS/AS and ends with the keyword END followed by the procedure name (optional) Syntax: CREATE OR REPLACE PROCEDURE <PROCEDURE_NAME>

(<PARAMETER> [MODE] <DATA TYPE>,)

IS/AS

[LOCAL VARIABLE DECLARATION]

BEGIN

PL/SQL EXECUTABLE STATEMENT

[EXCEPTION]

[EXCEPTION HANDLERS]

END [PROGRAM UNIT NAME];

In Syntax:

[REPLACE]: Option indicates that if the procedure exists, it will be dropped and replaced with the new version created by the statement.

<parameter>: Name of a PL/SQL variable whose value is passed to or populated by the calling environment, or both, depending on the mode being used

[Mode ]: Type of argument: IN (default), OUT, IN OUT <Data type>: Data type of the argument–can be any SQL / PLSQL data type.

PL/SQL block starts with either BEGIN or the declaration of local variables and ends with either END or END procedure_name.

Page 18 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 19: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Example: CREATE OR REPLACE PROCEDURE Addproduct(

V_prdouct_code Varchar2(100);

V_prdouct_name Varchar2(100);) AS

BRGIN

INSERT INTO product_dim (product_key,

product_code,

product_name)

VALUES (product_sequence.nextval,

v_product_code,

v_product_name);

COMMIT;

END Addproduct;

Formal parameters can have three modes: IN, OUT, or INOUT. Their features are described as follows: IN:

Default mode Takes the value inside the program Cannot be changed inside the subprogram

OUT:

Takes the value out of the subprogram Can be changed inside

INOUT: Takes the value inside a subprogram and brings the value out of the subprogram Example with in parameter: CREATE OR REPLACE PROCEDURE sp_addproduct(

IN V_prdouct_code Varchar2(100);

IN V_prdouct_name Varchar2(100);) AS

BRGIN

INSERT INTO product_dim (product_key,

product_code,

product_name)

VALUES (product_sequence.nextval,

v_product_code,

v_product_name);

COMMIT;

END sp_addproduct;

Page 19 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 20: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Example with OUT parameter: CREATE OR REPLACE PROCEDURE sp_calc_loanamount(

pv_loan_no IN NUMBER,

pv_loan_amount OUT NUMBER) IS

BEGIN

SELECT loan_amount*interest_rate INTO pv_loan_amount

FROM daily_pipeline_loan_fact

END sp_calc_loanamount;

Example of procedure with INOUT parameter: CREATE OR REPLACE PROCEDURE FORMAT_PHONE_NO ( V_PHONE IN OUT VARCHAR2)

IS

BEGIN

V_PHONE := ‘(‘ || SUBSTR(V_PHONE,1,3) || ‘)’ || SUBSTR (V_PHONE,4,3) || ‘-’ || SUBSTR(V_PHONE,7);

END FORMAT_PHONE_NO;

/

Executing the procedure: DECLARE

loan_id NUMBER;

loan_amount NUMBER;

BEGIN

loan_id := &loan_no;

Sp_calc_loanamount(loan_id,loan_amount);

DBMS_OUTPUT.PUT_LINE(‘The Total loan amount for loan number’ || loan_id || ‘ is’ ||loan_amount);

END;

/

Removing a Procedure: DROP PROCEDURE <procedure_name>

DROP PROCEDURE sp_calc_loanamount;

Functions

Function is a named PL/SQL block that returns a value. A function can be stored in the database as a schema object for repeated execution. A function is called as part of an expression. Functions can be used in a SELECT statement.

Page 20 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 21: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Syntax: CREATE OR REPLACE FUNCTION <FUNCTION NAME>

[(parameter1 [mode1] datatype1,

parameter2 [mode2] datatype2,

. . .)]

RETURN DATATYPE IS[<LOCAL DECLARATION>]

BEGIN

EXECUTABLE STATEMENTS

[EXCEPTION] [EXCEPTION HANDLERS]

END [FUNCTION_NAME];

In syntax:

[REPLACE]: Option indicates that if the function exists, it will be dropped and replaced with the new version created by the statement.

function_name: Name of the function. Parameter: Name of a PL/SQL variable whose value is passed into the function Mode: The type of the parameter; only IN parameters should be declared Datatype: Data type of the parameter RETURN datatype: Data type of the RETURN value that must be output by the function

Example: CREATE OR REPLACE FUNCTION fn_get_loan_amount ( pv_loan_id IN number)

RETURN NUMBER

IS

v_loanamount NUMBER;

BEGIN

SELECT loan_amount into V_loanamount

FROM daily_pipeline_loan_fact

WHERE loan_no = pv_loan_id ;

RETURN v_loanamount;

END fn_get_loan_amount;

Executing a Function: DECLARE

loan_id NUMBER;

loan_amount NUMBER;

BEGIN

loan_id := &loan_no;

loan_amount:=fn_get_loan_amount(loan_id);

DBMS_OUTPUT.PUT_LINE(‘The Total loan amount for loan number’ || loan_id || ‘ is’ ||loan_amount);

END;

Page 21 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 22: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Locations to Call User-Defined Function: Select list of a SELECT command Condition of the WHERE and HAVING clauses CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses VALUES clause of the INSERT command SET clause of the UPDATE command

Example: CREATE OR REPLACE FUNCTION fn_service_tax ( pv_loan_amount IN number)

RETURN NUMBER

IS

v_tax NUMBER;

BEGIN

RETURN (v_loanamount*0.12);

END fn_service_tax;

SELECT loan_no , fn_service_tax(loan_amount)

FROM daily_pipeline_loan_fact

To be callable from SQL expressions, a user-defined function must:

Be a stored function Accept only IN parameters Accept only valid SQL data types, not PL/SQL Specific types, as parameters Return data types that are valid SQL data types, Not PL/SQL specific types

Removing a Function: DROP FUNCTION <function_name>

DROP FUNCTION fn_service_tax;

All the privileges granted on a function are revoked when the function is dropped. The CREATE OR REPLACE syntax is equivalent to dropping a function and recreating it. Privileges granted on the function remain the same when this syntax is used.

Page 22 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 23: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Procedure VS Function

Procedures Functions

Execute as a PL/SQL statement Invoke as part of an expression

Do not contain RETURN clause in the header

Must contain a RETURN clause in the header

Can return none, one, or many values Must return a single value

Can contain a RETURN statement Must contain at least one RETURN statement

Packages

What is a Package? A package is a collection of Functions, Procedures, Global variables and cursors stored in server in compiled form. A package consists of 2 parts: Package Specification: This acts as an interface to the user applications. This part declares the, PL/SQL types, variables, constants, exception, cursor and sub-programs (Functions and procedures). This part is created using CREATE PACKAGE command. Package Body: It implements the specifications by defining the cursors and sub-programs. This part is created using CREATE PACKAGE BODY command. Oracle stores package specification and body separately in the data dictionary. A package specification can exists without a package body but not vice versa. An element of a package, whether it is a variable or a module, can either be Public When defined in the specification a public element can be referenced from other programs and PL/SQL blocks Private When defined only in the body of the package, but does not appear in the specification. A private element cannot be referenced outside of the package. It can only be referenced by other elements within the package The sub-programs that are present inside a package cannot exist separately as database objects. A package cannot be called by itself. Only the procedures and functions from within the package can be called with reference to the package using the dot (.) operator. When one sub-program is called, then all other sub-programs are also loaded into the memory, hence the subsequent call for any other modules becomes fast.

Page 23 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 24: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Package specification Syntax: CREATE [OR REPLACE] PACKAGE package name

IS|AS

public type and item declarations

subprogram specifications

END package_name;

The REPLACE option drops and recreates the package specification. Variables declared in the package specification are initialized to NULL by default.

Example package specification: CREATE PACKAGE pkg_total_amount

AS

PROCEDURE PROCEDURE sp_calc_loanamount

(pv_loan_no IN NUMBER , pv_loan_amount OUT NUMBER) ;

FUNTION fn_service_tax ( pv_loan_amount IN number);

END PK1;

Creating package body Syntax: CREATE [OR REPLACE] PACKAGE BODY package_name

IS|AS

private type and item declarations

subprogram bodies

END package_name;

The REPLACE option drops and recreates the package body. Identifiers defined only in the package body are private constructs. These are not visible

outside the package body. Example: CREATE PACKAGE BODY pkg_total_amount AS

PROCEDURE sp_calc_loanamount(pv_loan_no IN NUMBER, pv_loan_amount OUT NUMBER) IS

BEGIN

SELECT loan_amount*interest_rate INTO pv_loan_amount

FROM daily_pipeline_loan_fact

END sp_calc_loanamount;

FUNCTION fn_service_tax( pv_loan_amount IN number)

RETURN NUMBER

IS

v_tax NUMBER;

BEGIN

RETURN (v_loanamount*0.12);

END fn_service_tax;

END pkg_total_amount;

Page 24 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 25: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Removing a package: To remove the package specification and the body, use the following syntax: DROP PACKAGE package_name;

To remove the package body, use the following syntax: DROP PACKAGE BODY package_name;

Advantage: Better performance:

The entire package is loaded into memory when the package is first referenced. There is only one copy in memory for all users.

Overloading: With packages you can overload procedures and functions, which means you can create

multiple subprograms with the same name in the same package, each taking parameters of different number or data type.

Oracle Supplied Packages

Some Oracle server-supplied packages are: DBMS_DDL

DBMS_JOB

DBMS_OUTPUT

UTL_FILE

The DBMS_OUTPUT package enables you to output messages from PL/SQL blocks. Available procedures include:

PUT

NEW_LINE

PUT_LINE

GET_LINE

GET_LINES

ENABLE/DISABLE

Function or Procedure Description

PUT Appends text from the procedure to the current line of the line output buffer

NEW_LINE Places an end_of_line marker in the output buffer

PUT_LINE Combines the action of PUT and NEW_LINE

GET_LINE Retrieves the current line from the output buffer into the procedure

GET_LINES Retrieves an array of lines from the output buffer into the procedure

ENABLE/DISABLE Enables or disables calls to the DBMS_OUTPUT procedures

Page 25 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 26: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Summary

A procedure is a subprogram that performs an action. You can compile and save a procedure in the database. Parameters are used to pass data from the calling environment to the procedure. There are three parameter modes: IN, OUT, and IN OUT. A function is a named PL/SQL block that must return a value. A function is invoked as part of an expression. A function stored in the database can be called SQL statements. Generally, you use a procedure to perform action and a function to compute a value. A package is a compiled database object that logically groups PL/SQL types and

subprograms. It consists of two parts: specification and body. The specification is the interface to your applications; it declares the types, variables,

constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the specification.

Test Your Understanding

1. Create a procedure that will accept a percentage and JOB, and will show the reflection on the total salary. Calculate the total salary before the increment for the particular JOB and show the difference.

2. Create a procedure that will accept the LOAN amount and EMPNO as input and display the installment amount and number of installments to be paid. (Max loan amount will be his current salary * total number of years of service. Loan will be paid in equal monthly installment. Installment amount will be 1/10th of monthly salary)

3. What is a Subprogram? 4. What is the use of REPLACE keyword in creating procedure syntax? 5. What is the different mode of parameters? 6. What is difference between a procedure and a function? 7. Function received which type of parameter. 8. What is a package? 9. What are the advantages of package? 10. Give some example of Oracle supplied packages. 11. What are the different types of trigger? 12. What is the deference between row level trigger and statement level trigger? 13. What are different components of trigger?

Page 26 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 27: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 07: Triggers

Learning Objectives

After completing this session, you will be able to: Write Database Triggers

Appreciate Database Triggers

What is a Database Trigger? A database trigger is a stored program unit associated with a database table. Triggers are used to overcome the limitations of constraints and to supplement the declarative referential integrity while implementing complex business rules or to audit changes to data. Features of Database Triggers:

These are stored procedures that gets implicitly executed when some database-related event occurs

Can be applied on any Table/View Can be applied before the instruction is executed as well as after the execution Can work for any DML statements like INSERT, UPDATE and DELETE but not for SELECT Can be used to overcome the limitation of CHECK constraints

Syntax CREATE OR REPLACE TRIGGER <TRIGGER_NAME>

[BEFORE/AFTER] [INSERT/UPDATE/DELETE]

ON <TABLE_NAME>

[FOR EACH ROW [WHEN triggering_condition]]

trigger_body;

Components of Triggers

The main components of Database Triggers are the following: Trigger Timing: It means when a trigger should fire. The possible trigger timing is BEFORE, AFTER and INSTEAD OF

Trigger Event: The trigger event can be INSERT, UPDATE or DELETE Trigger Type: The type of trigger can be Statement or Row Trigger Body: This section specifies the action need to be performed by the trigger i.e. it

is the PL/SQL block that gets executed

Page 27 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 28: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Types of Triggers

There are two kinds of triggers in Oracle: Row Level:

o The action specified with the row level trigger will be executed for each affected row by the instruction for which the trigger is invoked

o These triggers will fire for every INSERT/UPDATE/DELETE on the table depending on the number of rows affected by the triggering event

o Should specify the keyword FOR EACH ROW Statement Level:

o They get fired in the table level once for each trigger event o These triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective

of the number of rows affected by the triggering event o To define a statement level trigger omit the FOR EACH ROW keyword in the trigger

specification

Create Triggers

Insert Triggers: BEFORE INSERT Trigger: A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation is executed. The syntax for a BEFORE INSERT Trigger is: CREATE or REPLACE TRIGGER trigger_name BEFORE INSERT ON TABLE [FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;

Page 28 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 29: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

AFTER INSERT Trigger: An AFTER INSERT Trigger means that Oracle will fire this trigger after the INSERT operation is executed. The syntax for an AFTER INSERT Trigger is:

CREATE or REPLACE TRIGGER trigger_name

AFTER INSERT

ON TABLE

[ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;

Update Triggers: BEFORE UPDATE Trigger: A BEFORE UPDATE Trigger means that Oracle will fire this trigger before the UPDATE operation is executed. The syntax for a BEFORE UPDATE Trigger is: CREATE or REPLACE TRIGGER trigger_name BEFORE UPDATE ON TABLE [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;

Page 29 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 30: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

AFTER UPDATE Trigger: An AFTER UPDATE Trigger means that Oracle will fire this trigger after the UPDATE operation is executed. The syntax for an AFTER UPDATE Trigger is: CREATE or REPLACE TRIGGER trigger_name AFTER UPDATE ON TABLE [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;

Delete Triggers: BEFORE DELETE Trigger: A BEFORE DELETE Trigger means that Oracle will fire this trigger before the DELETE operation is executed. The syntax for a BEFORE DELETE Trigger is: CREATE or REPLACE TRIGGER trigger_name BEFORE DELETE ON TABLE [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;

Page 30 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 31: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

AFTER DELETE Trigger: An AFTER DELETE Trigger means that Oracle will fire this trigger after the DELETE operation is executed. The syntax for an AFTER DELETE Trigger is: CREATE or REPLACE TRIGGER trigger_name AFTER DELETE ON TABLE [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;

While creating row level trigger, consider the following:

A row level trigger use: old and: new qualifiers to access the value of a column before or after the change of data caused by a DML operation.

Old and New qualifiers can only be used in row level triggers. DML operations on the table where a trigger is defined will cause mutating at the time of

trigger execution. The following table illustrates the old and new value of a database table column before

and after a DML operation: Managing triggers: Disable or reenable a database trigger: ALTER TRIGGER trigger_name DISABLE | ENABLE

Disable or reenable all triggers for a table: ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS

Recompile a trigger for a table: ALTER TRIGGER trigger_name COMPILE

Remove trigger: DROP TRIGGER trigger_name;

Page 31 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 32: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Order of Trigger Firing

Execute the BEFORE statement level trigger, if present For each row affected by the statement,

o Execute the BEFORE row-level trigger, if present. o Execute the statement itself. o Execute the AFTER row-level trigger, if present.

Execute the after statement-level trigger, if present

Summary

Triggers are stored procedures that gets implicitly executed when some database-related event occurs

Can work for any DML statements like INSERT, UPDATE and DELETE but not for SELECT Triggers can be row level and statement level. The action specified with the row level

trigger will be executed for each affected row by the instruction for which the trigger is invoked

The statement level triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective of the number of rows affected by the triggering event

Test Your Understanding

Write a trigger on the EMP table, so that after each insertion of new record, or updation of old one, the NOE column of the dept table gets updated. Add a column NOE to the dept table, which will record the number of rows for each department. In case of record updation the NOE of one department should be reduced and another should be incremented.

Page 32 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 33: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 10: Cursors and Exceptions

Learning Objectives

After completing this session, you will be able to: Explain cursors Explain the cursor attributes Write cursors Explain exceptions Explain pre-defined exception Explain user-defined exceptions Describe PRAGMA EXCEPTION_INIT Describe RAISE_APPLICATION_ERROR

Understand Cursors

A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the information within that SQL statement. In other words, a cursor is a SELECT statement that is defined within the declaration section of your PLSQL code. You will take a look at three different syntaxes for cursors. There are two types of cursors: Implicit and Explicit. An Implicit cursor is used for all other SQL statements. Implicit Cursors gives less programmatic control. In explicit cursor the cursor name is explicitly attached to a select statement The four PL/SQL steps necessary for explicit cursor processing are as follows:

Declare the cursor Open the cursor Fetch the results into PL/SQL variables Close the cursor

To use a cursor, it must be declared first. Syntax CURSOR cursor_name IS SELECT_statement;

A cursor without parameters CURSOR comp IS SELECT compid FROM company;

A cursor with parameters CURSOR comp (mcompid IN NUMBER) IS SELECT name FROM

company WHERE compid = mcomid;

Page 33 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 34: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Open Cursors: Once you have declared your cursor, the next step is to open the cursor The basic syntax to OPEN the cursor is as follows: OPEN cursor_name;

For example, you could open a cursor called c1 with the following command: OPEN c1;

While opening a cursor:

The values of the bind variables are examined Based on the bind variable the active set is determined The active set pointer is set to the first row.

Following is a function that demonstrates how to use the OPEN statement: CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number

IS cnumber number;

CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN

open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1;

RETURN cnumber; END;

Page 34 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 35: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Fetch Cursor

The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some type of operation can be performed on the data. After declaring and opening your cursor, the next step is to FETCH the rows from your cursor. Fetching a cursor has two forms: FETCH cursor_name INTO list_of_variables;

Or FETCH cursor_name INTO PL/SQL_record;

After each FETCH, the active set pointer is increased to next row. Thus, each FETCH will return successive rows in the active set, until the entire set is

returned. The %NOTFOUND attribute is used to determine when the active set has been retrieved.

The basic syntax for a FETCH statement is: FETCH cursor_name INTO <list of variables>;

For example, you could have a cursor defined as: CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in;

The command that would be used to fetch the data from this cursor is: FETCH c1 into cnumber;

This would fetch the first course_number into the variable called cnumber;

Close Cursor

The final step of working with cursors is to close the cursor once you have finished using it. The basic syntax to CLOSE the cursor is: CLOSE cursor_name;

For example, you could close a cursor called c1 with the following command: CLOSE c1;

Page 35 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 36: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Following is a function that demonstrates how to use the CLOSE statement: CREATE OR REPLACE Function FindCourse (name_in IN varchar2) RETURN number IS cnumber number;

CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN

open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1;

RETURN cnumber; END;

Cursor Attributes: While dealing with cursors, you may need to determine the status of your cursor. The following is a list of the cursor attributes that you can use:

Attributes Explanation %ISOPEN Returns TRUE if the cursor is open, FALSE if the cursor is closed

%FOUND Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. Returns NULL if cursor is open, but fetch has not been executed. Returns TRUE if a successful fetch has been executed. Returns FALSE if no row was returned.

%NOTFOUND Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. Return NULL if cursor is open, but fetch has not been executed. Returns FALSE if a successful fetch has been executed. Returns TRUE if no row was returned.

%ROWCOUNT Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. Returns the number of rows fetched.

Page 36 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 37: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Following is an example of how you might use the %NOTFOUND attribute. CREATE OR REPLACE Function FindCourse (name_in IN varchar2) RETURN number IS cnumber number;

CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN

open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1;

RETURN cnumber; END;

Cursor Examples: The following example shows a procedure that outputs a dynamic PLSQL cursor. The example states a problem and shows how to solve it. Question: In Oracle, I have a table called "wine" and a stored procedure that outputs a cursor based on the "wine" table. I've created an HTML Form where the user can enter any combination of three values to retrieve results from the "wine" table. My problem is that I need a general "select" statement that will work no matter what value(s), the user enters. Example: parameter_1= "Chianti" parameter_2= "10" parameter_3= wasn't entered by the user but I have to use in the select statement. And this is my problem. How to initialize this parameter to get all rows for column3? SELECT * FROM wine WHERE column1 = parameter_1 AND column2 = parameter_2 AND column3 = parameter_3;.

Page 37 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 38: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

The output of my stored procedure must be a cursor. Answer: To solve your problem, you will need to output a dynamic PLSQL cursor in Oracle. Let's take a look at how we can do this. We've divided this process into 3 steps. Step 1 - Table Definition First, we need a table created in Oracle called "wine". Below is the create statement for the wine table. create table wine ( col1 varchar2(40), col2 varchar2(40), col3 varchar2(40) );

We've made this table definition very simple, for demonstration purposes. Step 2 - Create package Next, we've created a package called "winepkg" that contains our cursor definition. This needs to be done so that we can use a cursor as an output parameter in our stored procedure. create or replace PACKAGE winepkg IS /* Define the REF CURSOR type. */ TYPE wine_type IS REF CURSOR RETURN wine%ROWTYPE; END winepkg;

This cursor will accept all fields from the "wine" table. Step 3 - Create stored procedure Our final step is to create a stored procedure to return the cursor. It accepts three parameters (entered by the user on the HTML Form) and returns a cursor (c1) of type "wine_type" which was declared in Step 2. The procedure will determine the appropriate cursor to return, based on the value(s) that have been entered by the user (input parameters). create or replace procedure find_wine2 (col1_in in varchar2, col2_in in varchar2, col3_in in varchar2, c1 out winepkg.wine_type) as

BEGIN

/* all columns were entered */ IF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in and wine.col2 = col2_in and wine.col3 = col3_in;

Page 38 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 39: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

/* col1 and col2 were entered */ ELSIF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) = 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in and wine.col2 = col2_in;

/* col1 and col3 were entered */ ELSIF (length(col1_in) > 0) and (length(col2_in) = 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in and wine.col3 = col3_in;

/* col2 and col3 where entered */ ELSIF (length(col1_in) = 0) and (length(col2_in) > 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col2 = col2_in and wine.col3 = col3_in;

/* col1 was entered */ ELSIF (length(col1_in) > 0) and (length(col2_in) = 0) and (length(col3_in) = 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in;

/* col2 was entered */ ELSIF (length(col1_in) = 0) and (length(col2_in) > 0) and (length(col3_in) = 0) THEN OPEN c1 FOR select * from wine where wine.col2 = col2_in;

/* col3 was entered */ ELSIF (length(col1_in) = 0) and (length(col2_in) = 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col3 = col3_in;

Page 39 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 40: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

END IF; END find_wine2;

Cursors FOR LOOP

Cursors FOR LOOP The cursor FOR loop is a shortcut to process explicit cursors. Implicit open, fetch, exit, and close occur. The record is implicitly declared.

Syntax: FOR record_name IN cursor_name LOOP

statement1;

statement2;

. . .

END LOOP;

Example: DECLARE

CURSOR c_product IS

SELECT product_key,product_name

FROM product_dim;

BEGIN

FOR i IN c_product LOOP

--implicit open and implicit fetch occur

IF i.product_key =1001 THEN

DBMS_OUTPUT.PUT_LINE ('Product ' || i.product_name);

END IF;

END LOOP; --implicit close and implicit loop exit

END;

The For Update Clause

The FOR UPDATE clause Use explicit locking to deny access for the duration of a transaction. Lock the rows before the update or delete.

Example: CURSOR c_product IS

SELECT loan_no,loan_amount

FROM daily_pipeline_loan_fact

WHERE product_key =1001

FOR UPDATE OF loan_amount NOWAIT;

Page 40 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 41: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

The FOR UPDATE clause identifies the rows that will be updated or deleted, then locks each row in the result set. This is useful when you want to base an update on the existing values in a row. In that case, you must make sure the row is not changed by another user before the update.

The WHERE CURRENT OF Clause

The WHERE CURRENT OF Clause Use cursors to update or delete the current row. Include the FOR UPDATE clause in the cursor query to lock the rows first. Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor.

Example: DECLARE

CURSOR c_loanamount IS

SELECT loan.loan_amount,loan.interest_rate,product.product_key

FROM daily_pipeline_loan_fact loan, product_dim product

WHERE loan.product_key= product.product_key

and product.product_key = 1001

FOR UPDATE OF loan_amount NOWAIT;

BEGIN

FOR i IN c_loanamount

LOOP

IF i.loan_amount < 1000 THEN

UPDATE daily_pipeline_loan_fact

SET interest_rate = i.interest_rate * 1.10

WHERE CURRENT OF c_loanamount;

END IF;

END LOOP;

END;

Understanding Exceptions

What is an Exception? Exceptions are errors raised whenever there is any in a particular PL/SQL block. This

causes a termination in the program by Oracle. Control then is transferred to the separate exception section of the program, if one exists, to handle the exception.

Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block and performs an illegal termination of the execution of the program.

PL/SQL traps and responds to errors using architecture of exception handler. Occurrence of any error in PL/SQL, whether a system error or an application error, an

exception is rose. This halts the processing in the current PL/SQL block's execution and control is

transferred to the separate exception section of the program, if one exists, to handle the exception.

The control never returns to that block after you finish handling the exception. Instead, control is passed to the enclosing block, if any.

Page 41 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 42: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

When an exception is raised, control passes to the exception section of the block. The exception section consists of handlers for all the exceptions.

EXCEPTION

WHEN exception_name THEN

sequence_of_statements1;

WHEN exception_name THEN

sequence_of_statements1;

END;

Types of Exceptions:

Predefined Exception User Defined Exception

Predefined Exceptions

Some exceptions are already defined in Oracle called the pre-defined exception. Mostly they are generated with the SELECT statement. They are raised implicitly at runtime. Every exception is associated with an error code. These exceptions are already defined in the STANDARD package (An Oracle supplied package).

Oracle Exception Name Oracle Error Explanation DUP_VAL_ON_INDEX ORA-00001 You tried to execute an INSERT or UPDATE statement

that has created a duplicate value in a field restricted by a unique index.

TIMEOUT_ON_RESOURCE ORA-00051 You were waiting for a resource and you timed out.

TRANSACTION_BACKED_OUT ORA-00061 The remote portion of a transaction has rolled back.

INVALID_CURSOR ORA-01001 You tried to reference a cursor that does not yet exist. This may have happened because you have executed a FETCH cursor or CLOSE cursor before opening the cursor.

NOT_LOGGED_ON ORA-01012 You tried to execute a call to Oracle before logging in.

LOGIN_DENIED ORA-01017 You tried to log into Oracle with an invalid username or password combination.

NO_DATA_FOUND ORA-01403 You tried one of the following: 1. You executed a SELECT INTO statement and no rows were returned. 2. You referenced an uninitialized row in a table. 3. You read past the end of file with the UTL_FILE package.

TOO_MANY_ROWS ORA-01422 You tried to execute a SELECT INTO statement and more than one row was returned.

ZERO_DIVIDE ORA-01476 You tried to divide a number by zero.

Page 42 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 43: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Exception functions: SQLCODE: Returns the numeric value for the error code. SQLERRM: Returns the message associated with the error number. Example: DECLARE

v_err_code NUMBER;

v_err_text VARCHAR2(255);

v_product_name product_dim.product_name%type;

BEGIN

SELECT product_name into v_product_name

FROM product_dim

WHERE product_id=&input_product_id;

dbms_output.put_line(v_product_name);

EXCEPTION

WHEN NO DATA FOUND THEN

v_err_code:=SQLCODE;

v_err_text:=SQLERM;

insert into errors values (v_err_code,v_err_text)

commit;

END:

User Defined Exception

Sometimes, it is necessary for programmers to name and trap their own exceptions - ones that aren't defined already by PL/SQL. These are called Named Programmer or User-Defined Exceptions. The syntax for the named programmer-defined exception in a procedure is as follows: CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS [declaration_section]

exception_name EXCEPTION;

BEGIN executable_section

RAISE exception_name ;

EXCEPTION WHEN exception_name THEN [statements]

WHEN OTHERS THEN [statements]

END [procedure_name];

Page 43 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 44: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

The syntax for the named programmer-defined exception in a function is: CREATE [OR REPLACE] FUNCTION function_name [(parameter [, parameter])] RETURN return_datatype IS | AS [declaration_section]

exception_name EXCEPTION;

BEGIN executable_section

RAISE exception_name ;

EXCEPTION WHEN exception_name THEN [statements]

WHEN OTHERS THEN [statements]

END [function_name];

Here is an example of a procedure that uses a named programmer-defined exception: CREATE OR REPLACE PROCEDURE add_new_order (order_id_in IN NUMBER, sales_in IN NUMBER) IS no_sales EXCEPTION;

BEGIN IF sales_in = 0 THEN RAISE no_sales;

ELSE INSERT INTO orders (order_id, total_sales ) VALUES ( order_id_in, sales_in ); END IF;

EXCEPTION WHEN no_sales THEN raise_application_error (-20001,'You must have sales in order to submit the order.');

WHEN OTHERS THEN raise_application_error (-20002,'An error has occurred inserting an order.');

END;

PRAGMA EXCEPTION_INIT

The pragma EXCEPTION_INIT associates an exception name with an Oracle error number. That lets you refer to any internal exception by name and to write a specific handler for it instead of using the OTHERS handler.

Some uncommon predefined errors numbers exists that does have names. Oracle allows to associate a user-defined name with a predefined error number (Oracle

Error).

Page 44 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 45: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

A pragma called EXCEPTION_INIT instructs the compiler to associate or initialize a programmer-defined exception with a specific Oracle error number.

It is associated with a predefined number in the declarative part. Syntax: PRAGMA EXCEPTION_INIT (EXCEPTION, ERROR_NUMBER);

Example: CREATE OR REPLACE PROCEDURE sp_addproduct(

IN V_prdouct_code Varchar2(100);

IN V_prdouct_name Varchar2(100);) AS

e_addproduct EXCEPTION;

PRAGMA EXCEPTION_INIT(e_addproduct,-22222);

BRGIN

UPDATE product_dim

SET product_name=V_prdouct_name

WHERE product_key=V_prdouct_code

IF SQL%NOTFOUND THEN

RAISE e_addproduct;

END IF;

COMMIT;

EXCEPTION WHEN e_addproduct THEN

DBMS_OUTPUT.PUT_LINE ('No such product id exist.')

END sp_addproduct;

RAISE_APPLICATION_ERROR

What is RAISE_APPLICATION_ERROR? The RAISE_APPLICATION_ERROR is a procedure that communicates application-specific errors from the server side (usually a database trigger) to the client-side application. This built-in procedure is the only mechanism available for communicating a server-side, programmer-defined exception to the client side in such a way that the client process can handle the exception. Error number should be of the range between –20000 and –20999. Error messages should be less than 512 characters. Syntax: RAISE_APPLICATION_ERROR (error_number in NUMBER, error_msg in VARCHAR2);

Example: CREATE OR REPLACE PROCEDURE sp_addproduct(

IN V_prdouct_code Varchar2(100);

IN V_prdouct_name Varchar2(100);) AS

BRGIN

UPDATE product_dim

SET product_name=V_prdouct_name

Page 45 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 46: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

WHERE product_key=V_prdouct_code

IF SQL%NOTFOUND THEN

RAISE_APPLICATION_ERROR(-20202,'This is not a valid product');

END IF;

COMMIT;

END sp_addproduct;

Summary

A SQL cursor is a private Oracle SQL working area. The implicit cursor is used by Oracle server to test and parse the SQL statements. Implicit cursors give less programmatic control. An implicit cursor is used for all other SQL statements. Explicit cursors are declared by the programmers. In explicit cursor the cursor name is

explicitly attached to a select statement. Explicit cursor handling requires declaring, opening, fetching, and closing cursor. Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block and

performs an illegal termination of the execution of the program. PL/SQL traps and responds to errors using architecture of EXCEPTION handler. Pre-defined exceptions are already defined in the STANDARD package. Exceptions can be pre-defined (built-in) and user-defined.

Test Your Understanding

1. What is a cursor? 2. What is difference between implicit cursor and explicit cursor? 3. What are the different cursors attributes? 4. What is the use of FOR UPDATE clause? 5. What is the use of WHERE CURRENT OF? 6. What is the advantage of cursor with a FOR LOOP? 7. What are the different types of exception? 8. What is PRAGMA EXCEPTION_INT? 9. What is RAISE_APPLICATION_ERROR? 10. What is the use of SQLCODE and SQLERM? 11. Create a cursor to print empno, ename, job, sal, hiredate and the increment amount for all

employees. Increment amount depends on the day of joining. Day of Joining Increment in % Friday 20 Wednesday 18 Thursday 17 For all others 15

Page 46 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 47: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 12: PL/SQL Collection, Record, and Varrays

Objectives

After completing this session, you will be able to: Define collections List the types of collection Declare collection Work with collection methods

Introduction

Collections and records are composite types that have internal components that can be manipulated individually, such as the elements of an array, record or table.

Collection

A collection is a ordered group of elements, all of the same type. It is a general concept that encompasses list, arrays, and other familiar data types. Each element has a unique subscript that determines its position in the collection. Collections work like the arrays found in most third-generation programming language. A collection is a ordered group of elements, all of the same type. It is a general concept that encompasses list, arrays, and other familiar data types. Each element has a unique subscript that determines its position in the collection. Collections work like the arrays found in most third-generation programming language. PL/SQL has two collection types: tables and varrays. Tables comes in two flavours:

o Index by tables (formerly called PL/SQL tables) o Nested tables

Index-by tables

Index-by tables: Also known as associative arrays. It lets you to look up elements using arbitrary numbers

and strings for subscript values. Are similar to one-dimensional arrays and are referenced like arrays of records. Since

index-by tables can be passed as parameters, they can be used to move columns of data into and out of database tables or between client-side applications and stored subprograms.

Are composed of two components: o Primary key of data type BINARY_INTEGER o Column of scalar or record data type

Can increase in size dynamically because they are unconstrained

Page 47 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 48: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Syntax: TYPE type_name IS TABLE OF

{column_type | variable%TYPE

| table.column%TYPE} [NOT NULL]

| table.%ROWTYPE

[INDEX BY BINARY_INTEGER];

identifier type_name;

Example: DECLARE

TYPE population_type IS TABLE OF NUMBER INDEX BY VARCHAR2(64);

country_population population_type;

continent_population population_type;

howmany NUMBER;

which VARCHAR2(64);

BEGIN

country_population('Greenland') := 100000; -- Creates new entry

country_population('Iceland') := 750000; -- Creates new entry

-- Looks up value associated with a string

howmany := country_population('Greenland');

dbms_output.put_line(howmany);

continent_population('Australia') := 30000000;

continent_population('Antarctica') := 1000; -- Creates new entry

continent_population('Antarctica') := 1001; -- Replaces previous value

-- Returns 'Antarctica' as that comes first alphabetically.

which := continent_population.FIRST;

dbms_output.put_line(which);

-- Returns 'Australia' as that comes last alphabetically.

which := continent_population.LAST;

dbms_output.put_line(which);

-- Returns the value corresponding to the last key, in this

-- case the population of Australia.

howmany := continent_population(continent_population.LAST);

dbms_output.put_line(howmany);

END;

Page 48 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 49: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Nested Table

Nested tables hold an arbitrary number of elements. They use sequential numbers as subscripts. Within the database, nested tables can be considered one-column database tables. Oracle does not store the rows of a nested table in any particular order. When the nested table is retrieve into a PL/SQL variable, the rows are given consecutive subscripts starting from one. That gives array-like access to individual rows. Example Store the borrower information and it's dependent information in the same table. CREATE OR REPLACE TYPE dependend_ty as object

( dependend_name VARCHAR2(50),

relationship VARCHAR2(20),

birth_date DATE) ;

CREATE TYPE dependend_nt AS TABLE OF dependend_ty ;

CREATE TABLE borrower

(borrower_id NUMBER,

borrowe_name VARCHAR2(50),

borrower_adress VARCHAR2(100),

dependends dependend_nt)

NESTED TABLE dependends STORE AS dependend_nt_tab;

INSERT INTO borrower

(10001,

'JAMES',

'D2-14 ,CA 9264',

dependend_nt(dependent_ty('JACOB','FATHER','31-MAR-1950'),

dependent_ty('RUBELA','MOTHER','25-MAR-1949')));

SELECT borrower_name,N.dependend_name,N.realtionship, N.birth_date

FROM borrower,TABLE(borrower.dependends) N ;

SET DESCRIBE DEPTH 2

DESC borrower

Difference between array and nested tables:

First, arrays have a fixed upper bound, but nested tables are unbounded. So, the size of a nested table can increase dynamically.

Second, arrays must be dense (have consecutive subscripts). So, individual elements cannot be deleted from an array. Initially, nested tables are dense, but they can be sparse (have non-consecutive subscripts).

Page 49 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 50: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Varrays

Items of type VARRAY are called varrays. Allow to associate a single identifier with an entire collection. Manipulate the collection as a whole and reference individual elements easily. To reference an element, use standard subscripting syntax.

CREATE OR REPLACE TYPE addresses_va AS VARRAY(3) of VARCHAR2(50) ;

CREATE TABLE borrower

(borrower_id NUMBER,

borrowe_name VARCHAR2(50),

borrower_adress VARCHAR2(100),

addresses addresses _VA);

INSERT INTO borrower

(10001,

'JAMES',

'D2-14 ,CA 9264',

addresses_va('address1','address2','address3'));

SELECT addresses FROM borrower

If you want to display the data from Varray in separates line then use TABLE function. SELECT b.borrower_name,n.*

FROM borrower b,TABLE(b.addresses) N;

Collection method

FIRST: Returns the index of the first element in the collection. LAST: Returns the index of the last element in the collection. PRIOR(n): Returns the index of the element prior to the specified element. NEXT(n): Returns the index of the next element after the specified element. EXTEND: Appends a single null element to the collection. EXTEND(n): Appends n null elements to the collection. EXTEND(n1, n2): Appends n1 copies of the n2th element to the collection. TRIM: Removes a single element from the end of the collection. TRIM(n): Removes n elements from the end of the collection. DELETE: Removes all elements from the collection. DELETE(n): Removes element n from the collection. DELETE(n1,n2): Removes all elements from n1 to n2 from the collection.

Page 50 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 51: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Summary

A collection is an ordered group of elements, all of the same type. Each element has a unique subscript that determines its position in the collection. PL/SQL has two collection types: Tables and Varrays. Tables come in two flavours index-by tables (formerly called PL/SQL tables) and nested

tables.

Test Your Understanding

1. What is a collection? 2. What are different types of collection? 3. What is the difference between nested table and Indexed table? 4. What is a Varray? 5. How do you describe a nested table? 6. List down all the methods that can be used with collection.

Page 51 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 52: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 14: Dynamic SQL

Learning Objectives

After completing this session, you will be able to: Explain dynamic SQL Execute dynamic SQL Describe bulk operations Describe FORALL Describe BULK COLLECT Differentiate soft parse and hard parse

Understand Dynamic SQL

What is Dynamic SQL? Dynamic SQL is an advanced programming technique that adds flexibility and functionality to applications. Dynamic SQL allows you to write SQL that will then write and execute more SQL for you. This can be a great time saver because you can:

Automate repetitive tasks. Write code that will work in any database or server. Write code that dynamically adjusts itself to changing conditions

Features of Dynamic SQL:

Dynamic SQL enables to write programs that reference SQL statements whose full text is not known until runtime

Before discussing dynamic SQL in detail, a clear definition of static SQL may provide a good starting point for understanding dynamic SQL

Static SQL statements do not change from execution to execution. The full text of static SQL statements are known at Compilation time that is not there in case of Dynamic SQL

Use of Dynamic SQL

Following are the uses of Dynamic SQL: Dynamic SQL lets execute SQL statements that are not supported in static SQL

Programs, data definition language (DDL) statements such as CREATE, data control Statement such as GRANT and session control statement such as ALTER SESSION

Dynamic SQL should be used in cases where static SQL does not support the operation you want to perform or in cases you do not know the exact SQL statements that must be executed by a PL/SQL procedure i.e. at Runtime

Page 52 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 53: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Execute Dynamic SQL

The EXECUTE IMMEDIATE Statement: The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic SQL statement or an anonymous PL/SQL block Syntax: EXECUTE IMMEDIATE dynamic_string

[INTO {define_variable[, define_variable]... | record}]

[USING [IN | OUT | IN OUT] bind_argument

[, [IN | OUT | IN OUT] bind_argument]...];

Where dynamic_string is a string expression that represents a SQL statement or PL/SQL

block. define_variable is a variable that stores a SELECTed column value, record is a user-

defined or %ROWTYPE record that stores a SELECTed row. bind_argument is an expression whose value is passed to the dynamic SQL statement

or PL/SQL block. The INTO clause, useful only for single-row queries, specifies the variables or Record into

which column values are fetched. For each column value returned by the query, there must be a corresponding, type-compatible variable or field in the INTO clause

Every bind argument must be put in the USING clause. If no parameter mode is specified, it defaults to IN. At run time, any bind arguments in the USING clause replace corresponding placeholders in the SQL statement or PL/SQL block. So, every placeholder must be associated with a bind argument in the USING clause. Numeric, character, and string literals are allowed in the USING clause, but Boolean literals (TRUE, FALSE, NULL) are not. To pass nulls to the dynamic string, a workaround must be used. Dynamic SQL supports all the SQL data types.

So, for example, define variables and bind arguments can be collections, LOBs, instances of an object type, and REFs.

Example using EXECUTE IMMEDIATE DECLARE

sql_stmt VARCHAR2(100);

plsql_block VARCHAR2(200);

my_deptno NUMBER(2) := 50;

my_dname VARCHAR2(15) := ’PERSONNEL’;

my_loc VARCHAR2(15) := ’DALLAS’;

emp_rec emp%ROWTYPE;

BEGIN

sql_stmt := ’INSERT INTO dept VALUES (:1, :2, :3)’;

EXECUTE IMMEDIATE sql_stmt USING my_deptno, my_dname,

my_loc;

sql_stmt := ’SELECT * FROM emp WHERE empno = :id’;

EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING 7788;

Page 53 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 54: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

EXECUTE IMMEDIATE ’DELETE FROM dept

WHERE deptno = :n’ USING my_deptno;

plsql_block := ’BEGIN emp_stuff.raise_salary(:id, :amt); END;’;

EXECUTE IMMEDIATE plsql_block USING 7788, 500;

EXECUTE IMMEDIATE ’CREATE TABLE bonus (id NUMBER, amt NUMBER)’;

sql_stmt := ’ALTER SESSION SET SQL_TRACE TRUE’;

EXECUTE IMMEDIATE sql_stmt;

END;

Example using the DBMS SQL package CREATE PROCEDURE insert_into_table (

Table_name VARCHAR2,

Deptnumber NUMBER,

Deptname VARCHAR2,

Location VARCHAR2) IS

Cur_hdl INTEGER;

Stmt_str VARCHAR2(200);

Rows_processed BINARY_INTEGER;

BEGIN

Stmt_str := 'INSERT INTO ' || Table_name || ' VALUES

(:deptno, :dname, :loc)';

-----Open cursor

cur_hdl := dbms_sql.open_cursor;

---- Parse cursor

dbms_sql.parse(cur_hdl, stmt_str,dbms_sql.native);

----- Supply binds

dbms_sql.bind_variable (cur_hdl, ':deptno', deptnumber);

dbms_sql.bind_variable (cur_hdl, ':dname', deptname);

dbms_sql.bind_variable (cur_hdl, ':loc', location);

---- Execute cursor

rows_processed := dbms_sql.execute(cur_hdl);

---- Close cursor

dbms_sql.close_cursor(cur_hdl);

END;

Understand Bulk Operations

What is the meaning of Bulk Operations? PL/SQL is very tightly integrated with the Oracle database SQL engine, but this tight

integration does not mean that there isn’t any overhead associated with executing SQL statements from PL/SQL

When a PL/SQL program executes, the procedural portions are executed by the PL/SQL engine, but all SQL statement are passed to SQL layer for execution, then data is passed back to the procedural engine

Page 54 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 55: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

The transfer of data back and forth from PL/SQL to SQL and back again is called context switching. The more switches occur the more performance degrades. Two new enhancements

BULK COLLECT and the FORALL statements allows to bulk together all of the context switches into a single switch and pass that to the SQL engine

Understand FOR ALL

What is the meaning of FOR ALL? A variation on the classic FOR LOOP that bundles together multiple DML statements based

on a collection Bulk DML using the FORALL statement will also take advantage of turning multiple context

switches into a single context switch. The FORALL statement must follow these simple rules: The body of the FORALL statement must contain a single DML operation.

The DML must reference collection elements, indexed by the index_row variable in the FORALL statement. The scope of the index_row variable is the FORALL statement only; you may not reference it outside of that statement.

Do not declare an INTEGER variable for index_row. It is declared implicitly by the PL/SQL engine.

The lower and upper bounds must specify a valid range of consecutive index numbers for the collection(s) referenced in the SQL statement.

Example of FOR ALL: PROCEDURE proc_bulk_collect IS

CURSOR cur_emp IS

SELECT emono

FROM emp;

TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY BINARY_INTEGER;

tab_emono tt_empno;

BEGIN

OPEN cur_emp;

FETCH cur_emp INTO BULK COLLECT tab_emono;

close cur_emp;

FORALL i IN tab_emono.FIRST..tab_emono.LAST LOOP

DELETE FROM new_emp

WHERE empno = tab_emono(i);

END LOOP;

end;

Page 55 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 56: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Understand BULK COLLECT

BULK COLLECT is an enhancement to explicit and implicit cursor query operation that allows the transfer of multiple rows of data in one trip to the SQL engine. Following is an example of BULK COLLECT: PROCEDURE proc_bulk_collect IS

CURSOR cur_emp IS

SELECT emono,ename

FROM emp;

TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY BINARY_INTEGER;

tab_emono tt_empno;

TYPE tt_ename IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER;

tab_ename tt_ename;

BEGIN

OPEN cur_emp;

FETCH cur_emp INTO BULK COLLECT tab_emono,tab_ename;

close cur_emp;

END;

Appreciate the difference between Soft Parse and Hard Parse

Soft parse: It is a Statement, which is parsed and already in the shared pool, those statements for re-execution need not require parsing if it is found in the shared Pool. A shorter process to getting the query result Hard parse: It is a statement, which is parsed every time during the execution is called hard parse. If we have to Hard Parse a large percentage of our queries, our system will function slowly and in some cases. Hard parse can be avoided by using bind variable in subprogram.

Summary

Dynamic SQL enables to write programs that reference SQL statement whose full text is not known until runtime.

Dynamic SQL lets execute SQL statements that are not supported in static SQL Programs.

The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic SQL statement or an anonymous PL/SQL block.

BULK COLLECT and the FORALL statements allows to bulk together all of the context switches into a single switch and pass that to the SQL engine.

Page 56 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 57: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Test Your Understanding

1. Which SQL statement PL/SQL support not supporting? 2. What is a dynamic SQL? 3. What is the use of EXECUTE IMMEDIATE? 4. What is BULCK COLLECT? 5. What is DBMS_SQL? 6. The following are the two Dynamic SQL statements. What is the main difference between

these two statements in the respect of execution? Begin

EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';

End;

/

CREATE OR REPLACE PROCEDURE CREATE_TABLE2 AS

cur integer;

rc integer;

BEGIN cur := DBMS_SQL.OPEN_CURSOR;

DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);

rc := DBMS_SQL.EXECUTE(cur);

DBMS_SQL.CLOSE_CURSOR(cur);

END;

Page 57 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 58: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Session 17: Oracle Utilities

Objectives

After completing this session, you will be able to: Describe the use of Export/Import and SQL Loader utilities. Describe the concept of Export/Import and SQL Loader utilities. Perform simple export and import operations. Load data into Oracle tables from operating system files using SQL*Loader

Introduction

There are some utilities in Oracle that can be used to archive, load data into tables and backup / recover tables and database. The utilities that will be discussed here:

Export Import SQL *Loader

Export and Import Utility: Overview

You can use these utilities to do the following: Archive Historical data Take backup ( At table / schema / database level ) Recover ( At table / schema / database level ) Move data between databases or machines Transfer tablespaces between databases. These utilities are run at OS level. You must have CREATE SESSION privilege on an Oracle Database. To export objects belonging to other user must have the EXP_FULL_DATABASE role. These utilities can be invoked using:

o Command Line interface o Interactive export prompts o Oracle Enterprise Manager

Oracle EXPORT utility

This utility is used provide a logical backup of: Database objects A Tablespace A schema Full database

Page 58 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 59: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Syntax: $ exp KEYWORD=value or KEYWORD=(value1,value2,...,valueN)

exp PARFILE=filename exp username/password /* To begin an interactive session */ exp username/password [keyword=value1,… | keyword2=value1..]..

Note: USERID must be the first parameter on the command line. Keywords and description ( default value):

USERID: Username/password FULL: Export entire file (N) BUFFER: Size of data buffer OWNER: List of owner usernames FILE: Output files (EXPDAT.DMP) TABLES: List of table names COMPRESS: Import into one extent (Y) RECORDLENGTH: Length of IO record GRANTS: Export grants (Y) INCTYPE: Incremental export type INDEXES: Export indexes (Y) RECORD: Track incr. export (Y) DIRECT: Direct path (N) TRIGGERS: Export triggers (Y) LOG: Log file of screen output STATISTICS: Analyze objects (ESTIMATE) ROWS: Export data rows (Y) PARFILE: Parameter filename CONSISTENT: Cross-table consistency(N) CONSTRAINTS: Export constraints (Y) OBJECT_CONSISTENT: Transaction set to read only during object export (N) FEEDBACK: Display progress every x rows (0) FILESIZE: Maximum size of each dump file FLASHBACK_SCN: SCN used to set session snapshot back to FLASHBACK_TIME: Time used to get the SCN closest to the specified time QUERY: Select clause used to export a subset of a table RESUMABLE: Suspend when a space related error is encountered(N) RESUMABLE_NAME: Text string used to identify resumable statement RESUMABLE_TIMEOUT: Wait time for RESUMABLE TTS_FULL_CHECK: Perform full or partial dependency check for TTS VOLSIZE: Number of bytes to write to each tape volume TABLESPACES: List of tablespaces to export TRANSPORT_TABLESPACE: Export transportable tablespace metadata (N)

Page 59 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 60: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

TEMPLATE: Template name which invokes iAS mode export Examples

1. exp hr/hr tables=(departments,employees) file=exp1.dmp log=exp1.log

2. exp system/manager full=y file=exp1.dmp log=exp1.log 3. exp system/manager fromuser=hr file=exp1.dmp log=exp1.log

Oracle Import utility

This utility is used to restore / recover: 1. A particular table 2. A schema 3. A tablespace 4. Full database

Syntax $ imp KEYWORD=value or KEYWORD=(value1,value2,...,valueN)

imp PARFILE=filename

imp username/password /* To begin an interactive session */

imp username/password [keyword=value1,… | keyword2=value1..]..

Note: USERID must be the first parameter on the command line. Keywords and Description (default):

USERID: Username/password FULL: Import entire file (N) BUFFER: Size of data buffer FROMUSER: List of owner usernames FILE: Input files (EXPDAT.DMP) TOUSER: List of usernames SHOW: Just list file contents (N) TABLES: List of table names IGNORE: Ignore create errors (N) RECORDLENGTH: Length of IO record GRANTS: Import grants (Y) INCTYPE: Incremental import type INDEXES: Import indexes (Y) COMMIT: Commit array insert (N) ROWS: Import data rows (Y) PARFILE: Parameter filename LOG: Log file of screen output CONSTRAINTS: Import constraints (Y)

Page 60 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 61: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

DESTROY: Overwrite tablespace data file (N) INDEXFILE: Write table/index info to specified file SKIP_UNUSABLE_INDEXES: Skip maintenance of unusable indexes (N) FEEDBACK: Display progress every x rows(0) TOID_NOVALIDATE: Skip validation of specified type ids FILESIZE: Maximum size of each dump file STATISTICS: Import precomputed statistics (always) RESUMABLE: Suspend when a space related error is encountered(N) RESUMABLE_NAME: Text string used to identify resumable statement RESUMABLE_TIMEOUT: Wait time for RESUMABLE COMPILE: Compile procedures, packages, and functions (Y) STREAMS_CONFIGURATION: Import streams general metadata (Y) STREAMS_INSTANITATION: Import streams instantiation metadata (N) VOLSIZE: Number of bytes in file on each volume of a file on tape

The following keywords only apply to transportable tablespaces

TRANSPORT_TABLESPACE import transportable tablespace metadata (N) TABLESPACES tablespaces to be transported into database DATAFILES datafiles to be transported into database TTS_OWNERS users that own data in the transportable tablespace set

Examples:

1. imp hr/hr tables=(departments,employees) rows=y file=exp1.dmp log=imp1.log

2. imp system/manager full=y file=exp1.dmp log=imp1.log 3. imp system/manager fromuser=hr file=exp1.dmp log=imp1.log

Page 61 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 62: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Oracle SQL *Loader utility

Oracle Database

Discard File

SQL *Loader

Log File

Bad File

Datafile / s

Control File

SQL*Loader loads data from external files into tables in an Oracle DB. This utility is run at OS level and not from within SQLPLUS. Some features are as follows:

Has a powerful data parsing engine which puts little limitation on the format of the data in the datafile.

Can load data from multiple datafiles during the same load session. Can load data into multiple tables during the same load session. Is character set aware (you can specify the character set of the data). Can selectively load data (you can load records based on the records' values). Can manipulate the data before loading it, using SQL functions. Can generate unique sequential key values in specified columns. Can use the operating system's file system to access the datafile(s). Can load data from disk, tape, or named pipe. Does sophisticated error reporting which greatly aids troubleshooting. Supports two loading "paths" -- Conventional and Direct.

Syntax $ sqlldr keyword=value [, keyword=value]

Page 62 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 63: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Keywords and values are as follows: userid: Username/password control: Control file name bad: Bad data file name data: Datafile name discard: Discard file name discardmax: Number of discards to allow (all) skip: Number of logical records to skip (0) load: Number of logical records to load (all) errors: Number of errors to allow (50) rows: Number of rows to bind array (64) bindsize: Size of bind array (nnnnn) silent: Suppress messages during run

Note:

1. If the values are specified in the above order, the keywords are not necessary. 2. Delimiters are either commas or spaces. 3. Any values not specified in the control line will either use the default value or be prompted.

Examples $ sqlldr scott/tiger control=loader.ctl

loader.ctl file: load data

infile 'c:\data\mydata.csv'

into table emp

fields terminated by "," optionally enclosed by '"'

( empno, empname, sal, deptno )

mydata.csv file: 10001,"Scott Tiger", 1000, 40 10002,"Frank Naude", 500, 20

Summary

There are some utilities in Oracle that can be used to archive, load data into tables and backup / recover tables and database. The utilities that will be discussed here:

Export Import SQL *Loader

Page 63 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 64: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Test Your Understanding

What are the different kinds of backup? How will you take logical backup of a table? Who can take logical backup of table? What are the different modes of logical backup? What roles/privileges are required to run the export utility? What are the minimum keywords required to run the export utility? What utilities can be used to load data into Oracle database? What are the different ways you can load data into database? What roles/privileges are required to run the import utility? Give the syntax to run import utility to load data into a database in another server. How is data loaded using sql *loader? What are the input files required to run sql *loader? What are the different types of loading that can be done using sql *loader? How do load into multiple tables in the same session? How do you load data using sql *loader without the input datafile?

Page 64 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 65: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

References

Websites

http://otn.oracle.com http://www.docnmail.com/learn/Oracle.htm

Books

Oracle 10g Complete Reference: Kevin Loney, George Koch, Oracle Press

Page 65 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

Page 66: Handout Oracle 10g PLSQL v1.0

Handout – Oracle 10g PL/SQL

Page 66 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved

C3: Protected

STUDENT NOTES: