Sei sulla pagina 1di 49

PL/SQL Part I

www.theoracletrainer.com

raghu@theoracletrainer.com

Contents

Structure of PL/SQL PL/SQL programming fundamentals Error Handling Cursor manipulation PL/SQL types Procedures and Functions Database triggers Introduction to Packages

www.theoracletrainer.com

raghu@theoracletrainer.com

PL/SQL
Procedural Language provided by ORACLE Is a technology and not a product PL/SQL is a block-structured language Used to create and store Oracle objects such as Stored Procedures, Functions and Database Triggers These objects can be called by client applications

www.theoracletrainer.com

raghu@theoracletrainer.com

PL/SQL
PL/SQL Blocks of code can be embedded in host languages Using PL/SQL, you can define and execute PL/SQL procedures, functions and packages PL/SQL engine executes PL/SQL blocks of code.It can reside in two environments The Oracle server Oracle tools

www.theoracletrainer.com

raghu@theoracletrainer.com

PL/SQL engine and Oracle Server


PL/SQL block

PL/SQL Engine
Procedural PL/SQL block Procedural Statement Statement Executor SQL SQL Statement Executor

www.theoracletrainer.com

Oracle Server raghu@theoracletrainer.com

Structure of PL/SQL

Declarations

Optional

Executable Statements Exception Handlers

Optional

www.theoracletrainer.com

raghu@theoracletrainer.com

Typical Structure of a PL/SQL Block


DECLARE variable Datatype; variable Datatype; BEGIN executable statements; EXCEPTION exception handlers; END ;

www.theoracletrainer.com

raghu@theoracletrainer.com

Identifiers
Definition An identifier is a name of a PL/SQL object. Properties Max 30 characters Must start with an alphabet Can include $, _, and # Cannot contain spaces,slashes and hyphens Should not be a reserved word PL/SQL is not case sensitive except within string and character literals www.theoracletrainer.com raghu@theoracletrainer.com

Comments
PL/SQL supports two comment styles: singleline and multi-line. Single-line comments begin with a double hyphen (--) anywhere on a line and extend to the end of the line Ex: -- DELETE FROM emp WHERE comm IS NULL; Multi-line comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines. Ex: /* The following line computes the area of a circle using pi, which is the ratio between the circumference and diameter. */ www.theoracletrainer.com raghu@theoracletrainer.com

Variables
Temporary storage of data Manipulation of stored values Reusability Ease of maintenance

www.theoracletrainer.com

raghu@theoracletrainer.com

Types of Variables
PL/SQL variables Scalar Scalar data types hold a single value. The main data types are those that correspond to column types in Oracle server tables: Pl/SQL also supports BOOLEAN variables. Composite Composite data types such as records, allow group of fields to be defined and manipulated in PL/SQL blocks. LOB (large objects) LOB data types hold values , called locators, that specify the location of large objects (such as graphic images) Non-PL/SQL variables: Bind and host variables

www.theoracletrainer.com

raghu@theoracletrainer.com

Declaring PL/SQL variables


Syntax Identifier [CONSTANT] datatype [NOT NULL] [:=|DEFAULT expr] Examples V_hiredate DATE; V_deptno NUMBER(2) NOT NULL:=10; V_location VARCHAR2(15):=BANGALORE; C_comm CONSTANT NUMBER:=1400;

www.theoracletrainer.com

raghu@theoracletrainer.com

www.theoracletrainer.com

raghu@theoracletrainer.com

Database objects
Table Basic unit of storage; composed of rows and columns View Logically represents subsets of data from one or more tables Sequence Generates primary key values Index Improves the performance of some quires Synonym Alternative name for an object

www.theoracletrainer.com

raghu@theoracletrainer.com

Creating a View
Syntax CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias(,alias].)] as subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]];

www.theoracletrainer.com

raghu@theoracletrainer.com

Contd..
OR REPLACE Re-creates the view if it already exists FORCE Creates the view regardless of weather or not the base table exists NOFORCE Creates the view only if base table exists (this is the default) View Is the name of the view Alias Specifies names for the expressions selected by the views query Subquery Is a complete SELECT statment WITH CHECK OPTION Specifies that only rows accessible to the view can be inserted or updated Constraint is the name assigned to the CHECK OPTION constraint WITH READ ONLY Ensures that no DML operations can be performed on this view

www.theoracletrainer.com

raghu@theoracletrainer.com

Synonym & Sequence


CREATE PUBLIC SYNONYM syn_name FOR owner.table_name;

CREATE SEQUENCE seq_name START WITH n INCREMENT BY n MAXVALUE n MINVALUE n CYCLE/NOCYCLE CACHE 20;
CREATE INDEX CREATE INDEX index_name ON table_name(column_name) COMPOSITE INDEXS CREATE INDEX index_name ON table_name(col1,col2,col3);

www.theoracletrainer.com

raghu@theoracletrainer.com

Anchored Declarations
%TYPE Enables you to declare the variables datatype being the same as the specified columns data type or a variables datatype %ROWTYPE Can declare a composite variable that is equivalent to a row in the specified table Anchored data types provide synchronization with database columns

www.theoracletrainer.com

raghu@theoracletrainer.com

Example
Using %TYPE DECLARE emp_name

emp.ename%TYPE;

Using %ROWTYPE DECLARE emp_rec emp%ROWTYPE;

www.theoracletrainer.com

raghu@theoracletrainer.com

Conditional & Sequential control

IF construct GOTO statement LOOPs simple or infinite loop FOR loop WHILE loop

www.theoracletrainer.com

raghu@theoracletrainer.com

IF Construct
IF <condition> THEN .... END IF;

IF <condition> THEN .... [ELSIF<condition > THEN] ...... [ELSE] ... END IF;

www.theoracletrainer.com

raghu@theoracletrainer.com

Example using IF construct


IF age >= 65 THEN INSERT INTO retired VALUES(name, age, lodging); elsif age <18 THEN INSERT INTO underage VALUES(name, age, lodging); ELSE INSERT INTO workforce VALUES(name, age, lodging); END IF;

www.theoracletrainer.com

raghu@theoracletrainer.com

GOTO Statement
To unconditionally transfer control. GOTO <labelname> <labelname> to be provided in double angle brackets << >>

www.theoracletrainer.com

raghu@theoracletrainer.com

Note:

At least one statement must follow a label You cannot transfer into an IF construct You cannot go to the middle of a LOOP You cannot transfer control from an executable section to an exception and vice versa You cannot use GOTO to enter a block

www.theoracletrainer.com

raghu@theoracletrainer.com

LOOP END LOOP


LOOP rem_balance := account_balance(accno); IF rem_balance < 100 THEN EXIT; ELSE decrement_balance(accno,withdraw_amt); END IF; END LOOP; Can also use EXIT WHEN to conditionally exit from a loop If you dont specify an exit condition, it becomes an infinite loop

www.theoracletrainer.com

raghu@theoracletrainer.com

FOR Loop
1.

FOR even_number IN 1..50 LOOP calc_values(even_number * 2); END LOOP;

2. FOR even_number IN REVERSE 1..10 LOOP calc_values(even_number*2); END LOOP;

www.theoracletrainer.com

raghu@theoracletrainer.com

FOR Loop (contd)

3.

FOR loop_index IN start_index .. end_index LOOP calc_values(even_number*2); END LOOP;

www.theoracletrainer.com

raghu@theoracletrainer.com

WHILE Loop

WHILE <condition> LOOP ..... END LOOP;

www.theoracletrainer.com

raghu@theoracletrainer.com

CURSORS
Oracle uses work areas to execute SQL statements and store processing information A cursor is a PL/SQL construct using which the work area can be named and the stored information can be accessed There are two kinds of cursors: implicit and explicit

www.theoracletrainer.com

raghu@theoracletrainer.com

Types of Cursors

Implicit Cursors Automatically created and destroyed by Oracle Created for every DML Explicit Cursors To be declared by the user and used using the open, fetch and close statements

www.theoracletrainer.com

raghu@theoracletrainer.com

Explicit Cursors-Usage
DECLARE CURSOR cursor_name IS <SELECT statement> OPEN OPEN cursor_name; FETCH FETCH cursor_name INTO cursor_rec CLOSE CLOSE cursor_name;

www.theoracletrainer.com

raghu@theoracletrainer.com

Cursor Declarations

DECLARE empname emp.name%TYPE; empsal emp.salary%TYPE; CURSOR emp_cur IS SELECT name,salary FROM WHERE dept=10;

emp

www.theoracletrainer.com

raghu@theoracletrainer.com

EXPLICIT CURSOR ATTRIBUTES


%ISOPEN Returns TRUE if cursor is open, FALSE if not %FOUND Returns TRUE if the last FETCH retrieved a row, FALSE if not %NOTFOUND Returns TRUE if the last FETCH did not retrieve a row %ROWCOUNT Returns the running count of number of rows fetched

www.theoracletrainer.com

raghu@theoracletrainer.com

cursor FOR loops


A cursor for loop can be used instead of open ,fetch and close statements This simplifies coding In a cursor FOR loop the loop index is implicitly declared as a record that represents a row in a database table. Cursor is automatically opened, rows are repeatedly fetched into fields of the record cursor gets automatically closed when all rows have been processed.

www.theoracletrainer.com

raghu@theoracletrainer.com

Implicit Cursor Attributes


SQL%FOUND Returns true if the last DML statement accessed one or more rows SQL%NOTFOUND Logical opposite of SQL%FOUND SQL%ROWCOUNT Returns the number of rows accessed by the last DML statement SQL%ISOPEN Always false

www.theoracletrainer.com

raghu@theoracletrainer.com

Cursors with FOR UPDATE


SELECTFor Update locks the rows before program changes them WHERE CURRENT OF can be used in the PL/SQL program to update the most recently fetched row of data

www.theoracletrainer.com

raghu@theoracletrainer.com

RECORDS
RECORDS TABLE BASED CURSOR BASED PROGRAMMER DEFINED SYNTAX TYPE <typename> IS RECORD (<field_name> <datatype>,.....); <recordname> <record_type>;

www.theoracletrainer.com

raghu@theoracletrainer.com

ADVANTAGES OF RECORDS
Data Abstraction Aggregate operations Leaner and cleaner code

www.theoracletrainer.com

raghu@theoracletrainer.com

PL/SQL Tables

One Column, One Primary key Column any scalar data type; Primary key is BINARY_INTEGER Can refer using the primary key value

www.theoracletrainer.com

raghu@theoracletrainer.com

PL/SQL Tables
Data structure that contains multiple data items that are the same data type Each table item has a key and a value Column any scalar data type; Primary key is BINARY_INTEGER Used to create a lookup table that is stored in memory to improve processing speed Comparable to a single dimension Array

www.theoracletrainer.com

raghu@theoracletrainer.com

PL/SQL tables
Cannot assign values directly ename_tab ENameTabType = (Nam1, Name2) --Not allowed Cannot reference in INTO clause SELECT ename INTO ename_tab FROM emp; --Not allowed

www.theoracletrainer.com

raghu@theoracletrainer.com

Exception Handling

PL/SQL traps errors using exception handlers. Types of exceptions Named System exceptions Unnamed System exceptions Programmer defined exceptions

www.theoracletrainer.com

raghu@theoracletrainer.com

Named System Exceptions


Common errors that have been given predefined names that appear instead of error numbers
Error Code ORA-00001 ORA-01001 ORA-01403 ORA-01422 Exception Name DUP_VAL_ON_INDEX INVALID_CURSOR NO_DATA_FOUND TOO_MANY_ROWS Description Unique constraint violated Illegal cursor operation Query returns no records Query returns more rows than expected Division by zero Invalid numeric conversion Error in arithmetic or numeric function operation

ORA-01476 ZERO_DIVIDE ORA-01722 INVALID_NUMBER ORA-06502 VALUE_ERROR

www.theoracletrainer.com

raghu@theoracletrainer.com

User defined exceptions


PL/SQL does not distinguish between system errors and user defined errors. It handles both exceptions in the exception section. Example: DECLARE out_of_balance EXCEPTION;

www.theoracletrainer.com

raghu@theoracletrainer.com

User defined exceptions - Example


declare out_of_balance exception; begin If (balance < 0) then RAISE out_of_balance; EXCEPTION WHEN out_of_balance THEN dbms_output.put_line (error); END;

www.theoracletrainer.com

raghu@theoracletrainer.com

Unnamed system exceptions


These are system errors which are not named explicitly by PL/SQL. This can be handled by using PRAGMA EXCEPTION_INIT. PRAGMAS are processed at COMPILE time.

www.theoracletrainer.com

raghu@theoracletrainer.com

PRAGMA EXCEPTION_INIT
Eg: an integrity violation condition like referential integrity violation returns a negative sqlcode but this is not named explicity by PL/SQL Associates an ORACLE error code with a user defined Exception

www.theoracletrainer.com

raghu@theoracletrainer.com

Exception Handling in Nested Program Blocks


DECLARE variable declarations BEGIN program statements

DECLARE exception_A BEGIN RAISE exception_A EXCEPTION exception_A error handler END;
additional program statements EXCEPTION error handling statements END;

If an exception is raised and handled in an inner block, program execution resumes in the outer block

Exception is raised and handled in inner block Program execution resumes here Exceptions raised in inner blocks can be handled by exception handlers in outer raghu@theoracletrainer.com blocks

www.theoracletrainer.com

SQLCODE and SQLERRM


SQLCODE returns the ORACLE error number(generally negative) SQLERRM returns corresponding error message For user defined exceptions SQLCODE returns +1 and returns message Userdefined Exception

www.theoracletrainer.com

raghu@theoracletrainer.com

Potrebbero piacerti anche