Vous êtes sur la page 1sur 47

Introduction to PL/SQL

PL/SQL Architecture
PL/SQL Engine PL/SQL Block PL /SQL Block Procedural SQL Procedural statement executor

SQL statement executor

Oracle Server

PL/SQL Block structure

[DECLARE]1 BEGIN [EXCEPTION] END;


1

[ ] 1 optional keywords are marked by square brackets BEGIN & END keywords are mandatory
3

Comments in PL/SQL block


Two hyphens(--) placed in the beginning of any statement would be considered as comment Multi-line comments (C style) are also allowed which begins with /* and ends with */ DECLARE Nesting of comments are not allowed, similar to C --declaration of variables language BEGIN syntax
/* SQL and PL/SQL statement(s) */ END;

Named PL/SQL blocks (1 of 2)


PL/SQL blocks can have a name Named blocks have an additional section called HEADER HEADER conveys the name of the block and whether the block is a PROCEDURE or a FUNCTION If the named PL/SQL block is a FUNCTION then we have to specify the data type of value it would be returning

When the block is run, it does not execute immediately, rather it compiles and stores it in the database for later execution
5

Named PL/SQL blocks (2 of 2)


Other procedures and functions can be invoked within a named PL/SQL block Parameters can be passed to and returned from a named PL/SQL block
CREATE [ OR REPLACE ] PROCEDURE block_name(p_param DATATYPE)

IS/AS
--declaration of variables BEGIN --SQL and PL/SQL statements EXCEPTION --error handling END;

Variables
Variables
Variables are memory regions used to hold data Type of value stored is decided by the data type Declared in the DECLARE section

Scalar datatype
A scalar datatype can hold a single value Subcategories

7

Character/String Number Boolean Date/Time

Variables
Syntax
variable_name datatype [ := value ]

Variables defined as NOT NULL initialized

also have to be

Variables
Examples on Character/String
SQL> DECLARE 2 v_productcategory VARCHAR2(20) :='Mobilephone';

Variables
Boolean
Used for storing boolean value such as TRUE, FALSE, and NULL Do not attempt to print or display the value stored SQL> DECLARE in boolean variable, as it is not possible 2 v_test BOOLEAN;
3 4 5 6 BEGIN v_test:='TRUE'; END; --Wrong v_test:= TRUE; --Correct

10

Variables
Date
Used for storing DATE Stores the century, year, month, day, hour, minute, second

Timestamp SQL> DECLARE

Used storing the date and time 2 for v_transactiondate DATE:= SYSDATE; 3 v_billingdate TIMESTAMP := SYSTIMESTAMP; Provides sub second time upto nine digits(the default . . . is.six) . .

11

DBMS_OUTPUT.PUT_LINE (1 of 2)
DBMS_OUTPUT.PUT_LINE
An oracle supplied packaged procedure
DBMS_OUTPUT is a package and PUT_LINE is a procedure within the package The string which has to be printed should be specified in parenthesis, following the PUT_LINE keyword Using SET SERVEROUTPUT ON this package should be enabled in SQLPLUS
12

DBMS_OUTPUT.PUT_LINE (2 of 2)
SQL> SET SERVEROUTPUT ON SQL> DECLARE 2 v_productcategory VARCHAR2(20) :='Mobile Phone';

3
6 7 8 9 10 11 12 13 /

v_transactiondate DATE:= SYSDATE;


v_billingdate TIMESTAMP := SYSTIMESTAMP; v_test BOOLEAN:=TRUE; BEGIN DBMS_OUTPUT.PUT_LINE(v_productcategory); DBMS_OUTPUT.PUT_LINE(v_transactiondate); DBMS_OUTPUT.PUT_LINE (v_billingdate); END;

Mobile Phone 10-MAR-09 10-MAR-09 03.39.27.845000 PM


13

declarations

declarations %TYPE
Usage 1 : Declare variables that directly maps to a column definition in the database
SQL> DECLARE 1 -- variablename 2 . . . . . . . . TABLENAME.COLUMNNAME%TYPE; --Syntax v_itemcode ITEM.ITEMCODE%TYPE;

%rowtype
Used for record Declare D dept%rowtype; Refer to fields d.deptno; d.deptname;

Accepting input in PL/SQL


Declare the variables in the declaration section of PL/SQL block Accept the value for variables in the executable block Display the accepted values as shown below SQL> SET SERVEROUTPUT ON SQL> DECLARE 2 3 4 5 6 7 old new STN001 PL/SQL procedure successfully completed.
17

v_itemname VARCHAR2(30); BEGIN v_itemname :='&v_item'; DBMS_OUTPUT.PUT_LINE(v_itemname); END; / 4: 4: v_itemname :='&v_item'; v_itemname :='STN001';

Enter value for v_item: STN001

Operators & Expressions

Operators & Expressions


Concatenation Operator ( || ) Arithmetic Operators( +, -, *, /,**) Relational Operators( =, !=, <, >, <=, >=) Logical Operators (AND, OR and NOT)
19

Concatenation Operator
|| is the concatenation operator Concatenates two or more strings together

DECLARE v_customername varchar2(10):=John'; BEGIN v_customername := v_customername || '10'; DBMS_OUTPUT.PUT_LINE('value of v_customername : '|| v_customername); END;

Do not use || instead of Logical operator OR

value of v_customername : John10

20

Arithmetic Operator - Addition


DECLARE v_reorderlevel NUMBER; BEGIN v_reorderlevel := v_reorderlevel+10; -- NULL +10 DBMS_OUTPUT.PUT_LINE(value of v_reorderlevel : '|| v_reorderlevel); END;

Value of v_reorderlevel :

(NULL)

Addition of NULL with any number is NULL Only numeric and date data types can be used along with arithmetic operators
21

Nested PL/SQL blocks (1 of 4)


A PL/SQL block defined within another PL/SQL block is called nested PL/SQL block Can be nested in the executable section or in exception handling section One or more nested blocks can be present within an anonymous PL/SQL block Overlapping of nested blocks are not allowed
22

Nested PL/SQL blocks (2 of 4)


DECLARE --declaration of variables in the enclosed block BEGIN --SQL and PL/SQL statement(s) DECLARE --- declaration of variables in the nested block BEGIN

-- SQL & PL/SQL statement(s) in nested block


END; DECLARE -- declaration of variables in the nested block BEGIN -- SQL & PL/SQL statement(s) in nested block END; --SQL and PL/SQL statement(s) END;
23

Nested PL/SQL blocks (3 of 4)


DECLARE --declaration of variables in the enclosed block BEGIN --SQL and PL/SQL statement(s) DECLARE -- declaration of variables in the nested block BEGIN -- SQL & PL/SQL statement(s) in nested block

DECLARE
-- declaration of variables BEGIN -- SQL and PL/SQL statement(s) END; END; --SQL and PL/SQL statement(s) END;
24

Scope of variables(1 of 3)
Variables declared in the DECLARE section would be visible in the EXECUTABLE section and EXCEPTION section Lifetime of variables declared in the nested block will be only within the nested block

Variables declared in the outermost block are visible in all the nested blocks
25

Scope of variables (2 of 3)
Scope of the variable is from DECLARE to its END
ERROR because scope of the variable is within the inner DECLARE to its END. identifier 'V_PRICE' must be declared

DECLARE v_qoh NUMBER:=10; BEGIN DECLARE v_price NUMBER:=20; BEGIN DBMS_OUTPUT.PUT_LINE('The value of v_qoh: '||v_qoh); DBMS_OUTPUT.PUT_LINE('The value of v_price: '||v_price); END; DBMS_OUTPUT.PUT_LINE('The value of v_qoh: '||v_qoh); DBMS_OUTPUT.PUT_LINE('The value of v_price: '||v_price); END;

26

PL/SQL Conditional Constructs

IF-THEN
DECLARE v_qoh NUMBER :=10; v_itemrequired NUMBER :=&b_itemrequired; BEGIN IF v_itemrequired>v_qoh THEN DBMS_OUTPUT.PUT_LINE('Item not available '); END IF; END;

IF condition THEN action; END IF;

Enter value for b_itemrequired: 11 old 3: v_itemrequired NUMBER :=&b_itemrequired; new 3: v_itemrequired NUMBER :=11; Item not available
28

IF-THEN-ELSE
IF condition THEN action; ELSE action; END IF;
DECLARE --Comparing NUMBER datatypes v_qoh NUMBER :=10; v_itemrequired NUMBER :=&b_itemrequired; BEGIN IF v_itemrequired > v_qoh THEN DBMS_OUTPUT.PUT_LINE('Item not available '); ELSE DBMS_OUTPUT.PUT_LINE('Item available '); END IF; END;

Enter value for b_itemrequired: 9 old 3: v_itemrequired NUMBER :=&b_itemrequired; new 3: v_itemrequired NUMBER :=9; Item available
29

IF-THEN-ELSIF
DECLARE v_qoh NUMBER :=10; v_itemrequired NUMBER :=&b_itemrequired; BEGIN IF v_itemrequired>v_qoh THEN DBMS_OUTPUT.PUT_LINE('Item not available '); ELSIF v_itemrequired=10 THEN DBMS_OUTPUT.PUT_LINE('Item available but no more stock '); ELSE DBMS_OUTPUT.PUT_LINE('Item not available); END IF; END;

IF condition THEN action; ELSIF condition THEN action; [ELSE action;] END IF;

30

LOOP
LOOP action END LOOP;
BEGIN LOOP DBMS_OUTPUT.PUT_LINE('I AM IN LOOP!!!'); END LOOP; END;
This is an infinite LOOP!!!

DECLARE v_price NUMBER:=1; BEGIN LOOP DBMS_OUTPUT.PUT_LINE('Price: '||v_price); v_price:=v_price+1; EXIT WHEN v_price >5; END LOOP; END;

OUTPUT: --------Price: 1 Price: 2 Price: 3 Price: 4 Price: 5

31

Numeric FOR Loop


FOR counter IN low_number .. high_number LOOP action; END LOOP;

BEGIN FOR v_price IN 1..5 LOOP DBMS_OUTPUT.PUT_LINE('Price: '||v_price); END LOOP; END;

OUTPUT: --------Price: 1 Price: 2 Price: 3 Price: 4 Price: 5

The variable is automatically declared and initialized


32

WHILE Loop
WHILE condition LOOP action; END LOOP;

DECLARE v_price NUMBER:=1; BEGIN WHILE v_price <=5 LOOP DBMS_OUTPUT.PUT_LINE('Price: '||v_price); v_price:=v_price+1; END LOOP; END;

OUTPUT: --------Price: 1 Price: 2 Price: 3 Price: 4 Price: 5

33

Using SQL SELECT in PL/SQL


SELECT select_list [INTO variable_list] FROM table_list [WHERE where_clause]

[ORDER BY column_list];

Only one row value can be returned to the variable_list If no value is returned then the No data found exception is thrown

If more than one record is returned then the Exact fetch returns more than requested number of rows exception is thrown.

34

Using SQL SELECT in PL/SQL


-- Write a PL/SQL block to display the quantity on hand for -- an item with itemid STN001 DECLARE v_qtyonhand item.qtyonhand%TYPE; BEGIN SELECT qtyonhand INTO v_qtyonhand FROM item WHERE itemid= STN001; DBMS_OUTPUT.PUT_LINE(Qty On Hand : '||v_qtyonhand); END; What would you do, if you want to select all the columns from item table where itemid is STN001 ?

35

Composite datatype
Is a datatype which can store more than one value All the values could be homogeneous or heterogeneous in nature meaning, values belonging to similar or different datatypes are stored collectively Especially useful for creation of record variables To create a record variable named v_itemrec which in turn stores ITEMID, ITEMNAME, QTYONHAND collectively we use %ROWTYPE After declaration, v_itemrec can hold only QTYONHAND one record at ITEMID ITEMNAME any point of time =
v_itemrec
36

1001

Pencil

50

%ROWTYPE
For declaring record variable, we use %ROWTYPE
Syntax: Example: recordvariablename tablename%ROWTYPE;

SQL> DECLARE

The above declaration anchors the v_itemrec record variable to all columns in the ITEM table Individual column names and their datatypes in record variable will be the same as that of the base table column names and definitions

v_itemrec item%ROWTYPE;

If any underlying column definition is modified, the change would be reflected in the structure of record variable, the next time the PL/SQL block is run or compiled

37

%ROWTYPE
To select all the columns from item table where itemid is STN001 using record variable SQL> SET SERVEROUTPUT ON SQL> DECLARE

2
3 4 5 6

v_itemrec item%ROWTYPE;
BEGIN SELECT * INTO v_itemrec FROM item WHERE itemid=STN001; DBMS_OUTPUT.PUT_LINE( v_itemrec.itemid); DBMS_OUTPUT.PUT_LINE( v_itemrec.itemname);

7
SQL> /

DBMS_OUTPUT.PUT_LINE( v_itemrec.qtyonhand);

8 END;

STN001 Pen 250 PL/SQL procedure successfully completed.


38

Using SQL INSERT in PL/SQL


INSERT INTO table_name[(column_list)] VALUES select_statement | (value_list);

--Inserting values to supplier table directly by providing

INSERT can be used in PL/SQL block as it is in --values SQL BEGIN INTO supplier(supplierid, INSERT The following example is a suppliername, direct insertion of suppliercontactno) VALUES ('S001','Reynolds','0012233'); values to the respective columns END;
39

Using SQL INSERT in PL/SQL


--Inserting values to supplier table by accepting from end user DECLARE v_supplierid supplier.supplierid%TYPE; v_suppliername supplier.suppliername%TYPE; v_suppliercontactno supplier.suppliercontactno%TYPE; BEGIN

v_supplierid:='&supplierid';
v_suppliername:='&suppliername'; v_suppliercontactno:='&suppliercontactno'; INSERT INTO supplier(supplierid, suppliername, suppliercontactNo ) VALUES (v_supplierid, v_suppliername, v_suppliercontactno); END;
40

Exception
Exception is an identifier in PL/SQL that is raised during execution It terminates the main body of action and transfers the control to the EXCEPTION section

Program execution will never return to the next statement, after the exception is raised
For example, if the exception is thrown in the nth line of a PL/SQL block, control will not return to the (n+1)th line i.e. (n+1)th line will not be executed and the program terminates

41

How to handle an exception?


Exception part of any PL/SQL block handles an exception If not handled in the exception part, the DECLARE exception is propagated to the calling BEGIN environment
Exception is raised

EXCEPTION
Exception is trapped

END;

42

Exception Syntax
EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1; statement2; . . . [WHEN exception3 [OR exception4 . . .] THEN statement1; statement2; . . .] [WHEN OTHERS THEN statement1; statement2; . . .] END;

43

Predefined Oracle Server Exception


Oracle Error ORA-1403 Predefined Exception NO_DATA_FOUND Description SELECT statement matches no rows

ORA-1422
ORA-0001 ORA-1476

TOO_MANY_ROWS
DUP_VAL_ON_INDEX ZERO_DIVIDE

SELECT statement matches more than one row


Unique constraint violated Division by zero

ORA-6502
ORA-1722

VALUE_ERROR
INVALID_NUMBER

Truncation, Arithmetic error


Conversion to a number failed. Ex. 2A is not valid

44

NO_DATA_FOUND - Predefined Exception


--Given an itemid display the itemname --If the given itemid is invalid, display Invalid Itemid SET SERVEROUTPUT ON DECLARE v_itemid item.itemid%TYPE; v_itemrec item%ROWTYPE; BEGIN v_itemid := '&v_itemid';

SELECT * INTO v_itemrec FROM ITEM WHERE itemid=v_itemid;


DBMS_OUTPUT.PUT_LINE('Item Name is '||v_itemrec.itemname); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('Invalid Input / item id');

END;
/ Enter value for v_itemid: STN04 Invalid Input / item id
45

User-defined exception
Declare an exception identifier in the declaration section

Raise the exception explicitly in the executable section using RAISE statement
Handle the exception in the exception handling part

46

User-defined Exception
--Given an itemid display the itemname --If the given itemid is invalid, display Invalid Itemid SET VERIFY OFF SET SERVEROUTPUT ON DECLARE v_itemid ITEM.ITEMID%TYPE; v_count number; e_Invalid_Itemid exception; BEGIN

v_itemid := '&v_itemid';
SELECT count(*) INTO v_count FROM ITEM WHERE itemid=v_itemid; IF v_count = 0 THEN RAISE e_Invalid_Itemid; END IF; DBMS_OUTPUT.PUT_LINE('Valid item id'); EXCEPTION WHEN e_Invalid_Itemid THEN DBMS_OUTPUT.PUT_LINE('Invalid Input / item id'); END;
47

Vous aimerez peut-être aussi