56
Base de Dados Avançadas Oracle10g PL/SQL Programming Nuno Rodrigues [email protected]

0910 Bda p01 Plsql En

  • Upload
    lsm96

  • View
    41

  • Download
    4

Embed Size (px)

Citation preview

Page 1: 0910 Bda p01 Plsql En

Base de Dados Avançadas

Oracle10g PL/SQL Programming

Nuno [email protected]

Page 2: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Summary

Introduction to PL/SQL

Basic PL/SQL

Block Structures

Handling Data in PL/SQL Blocks

Cursors and

Exception Handling

2

Page 3: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

The PL/SQL Language

PL/SQL is a procedural language, SQL is not

Proprietary Oracle language

Tightly integrated with SQL

Can increase performance by grouping

statements into blocks of code

Portable to any Oracle platform

Used within many Oracle tools

Stored program units can increase security

3

Page 4: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Application Models

Three main components

User interface or screens

Program logic (brains behind the screens)

Database

Most models are based on a two- or three-tier

structure

4

Page 5: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Two-tier Model

Commonly referred to as

client/server

Parts of the processing occur

both on the user’s computer

and the database server

Named or stored program

units are blocks of PL/SQL

code saved in the Oracle

database to provide server-

side processing

5

Page 6: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Three-tier Model

Thin client with no code loaded

on the user machine (browser

access)

Middle tier is the application

server – Forms server for

Oracle

Last tier is the database server

Processing load is on the

middle and last tier

Maintenance is simplified

6

Page 7: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

PL/SQL Block Structure

A PL/SQL block contains a DECLARE, BEGIN,

EXCEPTION, and END sections

Variables to hold values are declared

Scalar variables hold a single data value

Scalar variables can hold string values,

numbers, dates, and Boolean values

7

Page 8: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Commenting Code

Add comments within code to identify code

purpose and processing steps

Use /* */ to enclose a multiline comment

Use -- to add a single or partial line comment

8

Page 9: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Comment Examples

DECLARE

ex_prod_update EXCEPTION; --For UPDATE of no rows exception

BEGIN

/* This block is used to update product descriptions

Constructed to support the Prod_desc.frm app screen

Exception raised if no rows updated */

UPDATE bb_product

SET description = 'Mill grinder with 5 grind settings!'

WHERE idProduct = 30;

--Check if any rows updated

IF SQL%NOTFOUND THEN

RAISE ex_prod_update;

END IF;

EXCEPTION

WHEN ex_prod_update THEN

DBMS_OUTPUT.PUT_LINE('Invalid product id entered');

END;

9

Page 10: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Debugging in SQL*Plus

Use DBMS_OUTPUT.PUT_LINE statements

to display messages from execution

Must set SERVEROUTPUT ON

Place display messages throughout the

block to determine processing flow and

variable values

10

Page 11: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

PL/SQL Block Structure

DECLARE – create variables, cursors, and

types

BEGIN – SQL, logic, loops, assignment

statements

EXCEPTION – error handling

END – close the block

11

Page 12: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Variable Names Data Types

Begin with alpha

character

Up to 30 characters

Can contain upper and

lowercase letters,

numbers, _ , $ , #

Character – CHAR(n)

VARCHAR2(n)

Numeric – NUMBER(p,s)

Date – DATE

Boolean – BOOLEAN

12

Page 13: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Example DeclarationsDECLARE

lv_ord_date DATE;

lv_last_txt VARCHAR2(25);

lv_qty_num NUMBER(2);

lv_shipflag_bln BOOLEAN;

BEGIN

---- PL/SQL executable statements ----

END;

Note: Minimum requirements are variable name and data type

13

Page 14: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Variable InitializationDECLARE

lv_ord_date DATE := SYSDATE;

lv_last_txt VARCHAR2(25) := 'Unknown';

lv_qty_num NUMBER(2) := 0;

lv_shipflag_bln BOOLEAN := 'FALSE';

BEGIN

---- PL/SQL executable ----

---- statements ----

END;

Set a variable value when the variable is created

14

Page 15: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Variable Declaration Options

NOT NULL – the variable must always contain a

value

CONSTANT – the variable value can not be changed

in the block

DECLARE

lv_shipcntry_txt VARCHAR2(15) NOT NULL := 'US';

lv_taxrate_num CONSTANT NUMBER(2,2) := .06;

BEGIN

---- PL/SQL executable statements ----

END;

15

Page 16: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Calculations with Scalar Variables

multiplication

DECLARE

lv_taxrate_num CONSTANT NUMBER(2,2) := .06;

lv_total_num NUMBER(6,2) := 50;

lv_taxamt_num NUMBER(4,2);

BEGIN

lv_taxamt_num := lv_total_num * lv_taxrate_num;

DBMS_OUTPUT.PUT_LINE(lv_taxamt_num);

END;

/

16

Page 17: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Using SQL Functions

SQL functions such as MONTHS_BETWEEN can be used

within PL/SQL statements

17

Page 18: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Variable Scope

When nesting blocks, are

variables shared?

Inner blocks can use

variables from outer

blocks

18

Page 19: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Decision Structures

Control which statements in a PL/SQL block will

execute

Enables conditions to be tested to determine the

flow of statement execution

Most programming languages provide IF and

CASE statements to enable conditional

processing

19

Page 20: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Decision Structures

IF Statements

Simple IF

IF .. THEN ..

ELSE

END IF

IF .. THEN ..

ELSIF ..

ELSE

END IF

CASE Statements

Basic CASE

statement

Searched CASE

statement

CASE expression

20

Page 21: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Simple IF Statement

21

Page 22: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

IF/THEN/ELSE

22

Page 23: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

IF/THEN/ELSIF/ELSE

23

Page 24: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Logical Operators within IF

Logical operators (AND, OR) enable multiple

conditions to be checked

IF lv_state_txt = 'VA' OR lv_state_txt = 'PA' THEN

lv_tax_num := lv_sub_num * .06;

ELSE

lv_tax_num := lv_sub_num * .04;

END IF;

24

Page 25: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Basic CASE Statement

25

Page 26: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Searched CASE

26

Page 27: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

CASE Expression

27

Page 28: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Looping

Enables a statement or set of statements to be

executed more than once

A loop must provide instructions of when to end

the looping, or an ‘infinite’ loop will be produced

28

Page 29: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Basic LOOP

29

Page 30: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

WHILE Loop

30

Page 31: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

FOR Loop

31

Page 32: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

GOTO Statement

Jumping control that instructs the program

to move to another area of code to continue

processing

Most developers discourage the use of

GOTO as it complicates the flow of

execution

32

Page 33: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Host or Bind Variables

Reference host variables with a preceding colon in PL/SQL

BEGIN

:g_shopper := 25;

END;

/

WHERE idShopper = :g_shopper

AND orderplaced = 0;

Create host variable

Reference

host variable

33

Page 34: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Host/Bind Variables Declare

Using application environment variables to send

variables into and out of a PL/SQL block

SQL*Plus is an application environment

BEGIN

:g_state_txt := 'VA';

END;

/

34

Page 35: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Using Host/Bind Variables

DECLARE

lv_tax_num NUMBER(4,2);

lv_sub_num NUMBER(6,2) := 100;

BEGIN

IF :g_state_txt = 'VA' THEN

lv_tax_num := lv_sub_num * .06;

ELSIF :g_state_txt = 'CA' THEN

lv_tax_num := lv_sub_num * .08;

ELSE

lv_tax_num := lv_sub_num * .04;

END IF;

DBMS_OUTPUT.PUT_LINE(lv_tax_num);

END;

/

35

Page 36: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Include SQL within a Block

SQL statements can be embedded into the

executable area of a PL/SQL block

SELECT statements are embedded to query

needed data

An INTO clause is added to a SELECT

statement to move data retrieved into variables

36

Page 37: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Include SQL within a Block

SQL

Query – add

INTO clause

Assignment Statement

37

Page 38: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Including DML

DML statements can be

embedded into PL/SQL

blocks to accomplish data

changes

DML includes INSERT,

UPDATE, and DELETE

statements

38

Page 39: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Exercise

NEMP = ENCAR

NDEP = NDEP

EMP

NEMP NUMBER(4) not null

NDEP NUMBER(2) null

EMP_NEMP NUMBER(4) null

ENCAR NUMBER(4) null

NOME VARCHAR2(20) not null

FUNCAO VARCHAR2(12) null

DATA_ENTRADA DATE null

SAL NUMBER(7) null

PREMIOS NUMBER(4) null

DEP

NDEP NUMBER(2) not null

NOME VARCHAR2(15) not null

LOCAL VARCHAR2(15) null

DESCONTOS

ESCALAO NUMBER(2) not null

SALINF NUMBER(7) not null

SALSUP NUMBER(7) not null

39

Page 40: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Exercise

1. Update the PREMIOS attribute as follows:1. If # of employees > 10, 10% of average salary for

that department

2. If # of employees <3, 20% of the difference between the highest and lowest salaries

3. Otherwise, 2% * # of employees

4. President, gets an increase of 10% of the lowest salary * # of employees who get that salary

40

Page 41: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

%TYPE Attribute Use in variable declaration to provide data

type based on a table column

Ideal for declaring variables that will hold data

from the database

Minimizes maintenance by avoiding program

changes to reflect database column changes

Called an anchored data type

lv_basket_num bb_basket.idBasket%TYPE;

41

Page 42: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

%TYPE Example

42

Page 43: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

%ROWTYPE Attribute

Create record structure based on table structure

DECLARE

rec_shopper bb_shopper%ROWTYPE;

BEGIN

SELECT *

INTO rec_shopper

FROM bb_shopper

WHERE idshopper = :g_shopper;

DBMS_OUTPUT.PUT_LINE(rec_shopper.lastname);

DBMS_OUTPUT.PUT_LINE(rec_shopper.address);

DBMS_OUTPUT.PUT_LINE(rec_shopper.email);

END;

43

Page 44: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Record Data TypeDECLARE

TYPE type_basket IS RECORD (

basket bb_basket.idBasket%TYPE,

created bb_basket.dtcreated%TYPE,

qty bb_basket.quantity%TYPE,

sub bb_basket.subtotal%TYPE);

rec_basket type_basket;

lv_days_num NUMBER(3);

lv_shopper_num NUMBER(3) := 25;

BEGIN

SELECT idBasket, dtcreated, quantity, subtotal

INTO rec_basket

FROM bb_basket

WHERE idShopper = lv_shopper_num AND orderplaced = 0;

lv_days_num := SYSDATE - rec_basket.created;

END;

44

Page 45: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Cursors

Work area in which SQL statement is processed

Implicit cursor – declared automatically for DML

and SELECT statements

Explicit cursor – declared and managed

programmatically to handle a set of rows

returned by a SELECT statement

Cursor variable – reference or pointer to a work

area or cursor

45

Page 46: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Cursor Attributes

Attribute

Name

Data

type

Description

%ROWCOUNT Number Number of rows affected by the SQL

statement

%FOUND Boolean TRUE if at least one row is affected by

the SQL statement, otherwise FALSE

%NOTFOUND Boolean TRUE if no rows are affected by the SQL

statement, otherwise FALSE

46

Page 47: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Implicit Cursor

47

Page 48: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Explicit Cursor

Step Step Activity Activity Description

1 DECLARE Creates a named cursor identified by a SELECT

statement. The SELECT statement does not

include an INTO clause. Values in the cursor are

moved to PL/SQL variables with the FETCH step.

2 OPEN Processes the query and creates the active set of

rows available in the cursor.

3 FETCH Retrieves a row from the cursor into block

variables. Each consecutive FETCH issued will

retrieve the next row in the cursor until all rows

have been retrieved.

4 CLOSE Clears the active set of rows and frees the

memory area used for the cursor.

48

Page 49: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Explicit Cursor ExampleDeclare cursor

Declare record type

and variable

Open cursor

Fetch a row from the cursor

Close cursorCalculate tax amount

Check if row returned from fetch

49

Page 50: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Cursor FOR Loop

Handles tasks automatically for processing each

row returned by a cursor (record declaration,

fetch, ending loop)

Use FOR UPDATE and WHERE CURRENT OF

clauses for record locking

50

Page 51: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Cursor FOR Loop ExampleDECLARE

CURSOR cur_prod IS

SELECT type, price

FROM bb_product

WHERE active = 1

FOR UPDATE NOWAIT;

lv_sale bb_product.saleprice%TYPE;

BEGIN

FOR rec_prod IN cur_prod LOOP

IF rec_prod.type = 'C' THEN lv_sale := rec_prod.price * .9;

END IF;

IF rec_prod.type = 'E' THEN lv_sale := rec_prod.price * .95;

END IF;

UPDATE bb_product

SET saleprice = lv_sale

WHERE CURRENT OF cur_prod;

END LOOP;

COMMIT;

END;

51

Page 52: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Cursor Variable

More efficiently handles data returned by query

by returning a pointer to the work area rather

than the actual result set

The same cursor variable can be used for

different query statements

52

Page 53: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Cursor Variable ExampleDECLARE

TYPE type_curvar IS REF CURSOR;

cv_prod type_curvar;

rec_coff bb_coffee%ROWTYPE;

rec_equip bb_equip%ROWTYPE;

BEGIN

IF :g_choice = 1 THEN

OPEN cv_prod FOR SELECT * FROM bb_coffee;

FETCH cv_prod INTO rec_coff;

. . .

END IF;

IF :g_choice = 2 THEN

OPEN cv_prod FOR SELECT * FROM bb_equip;

FETCH cv_prod INTO rec_equip;

. . .

END IF;

END;

53

Page 54: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 200854

CURSOR (FOR vs OPEN … FETCH)

DECLARE

CURSOR C1 IS

SELECT NAME,ID

FROM EMPLOYEES;

reg C1%ROWTYPE;

BEGIN

OPEN C1;

LOOP

FETCH C1 INTO reg;

EXIT WHEN C1%NOTFOUND;

-- plsql statements --

END LOOP;

CLOSE C1;

END;

DECLARE

CURSOR C1 IS

SELECT NAME,ID

FROM EMPLOYEES;

BEGIN

FOR reg in C1

LOOP

-- plsql statements --

END LOOP;

END;

54

Page 55: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

CURSOR

DECLARE

CURSOR C1 (dip NUMBER)IS

SELECT NAME,ID

FROM EMPLOYEES WHERE DEPID=dip;

BEGIN

FOR reg in C1 (21)

LOOP

-- plsql statements --

END LOOP;

FOR reg in C1 (15)

LOOP

-- plsql statements --

END LOOP;

END;

55

Page 56: 0910 Bda p01 Plsql En

BDA - PLSQLNuno Rodrigues - 2008

Exercises

1. Insert into table TEMP the name and salary for

the employees who get the highest salaries

2. For each department, insert the name and

salary for the 2 employees with the lowest

salaries.

56