Sie sind auf Seite 1von 8

3/16/2006

The PL/SQL Language


What is PL/SQL? Oracles procedural extension to SQL. Supplements SQL with several high-level programming features such as block structure, variables, constants and types, the assignment statement, conditional statements, loops, customized error handling, and structured data. Properties: 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/16/2006 PL/SQL 2

PL/SQL
Lecture 1

Data Types and Variables


Oracle SQLs data types can be classified into 2 categories: scalar and composite. The scalar data types include all of the Oracle SQL data types and a few new ones. They are summarized as follows:
Category Numeric Data Type Binary_integer Natural Positive Number(p,s) char(n) varchar2(n) boolean date Description Integer in the range -2^31-1 to 2^31-1 Integer in the range 0 to 2^31 Integer in the range 1 to 2^31 Same as Oracle SQLs number, where p is the precision and s is the scale Fixed-length character string of length n Variable-length character string of maximum length n Boolean data type (true, false) Same as Oracle SQLs date
PL/SQL 4

Variables
Used to store numbers, character strings, dates, and other data values Avoid using keywords, table names and column names as variable names Must be declared with data type before use: variable_name data_type_declaration;

3/16/2006

Variables are declared in PL/SQL using the syntax


<variable-name> <datatype> [not null] [:=<initial-value>]

Constants are declared as follows:


<constant-name> constant <datatype> := <value>;

Examples
a binary_integer; cno number(5) not null :=1111; cname varchar2(30); commission real(5,2) :=12.5; maxcolumn constant integer(2) :=30; Hired_date date; done boolean;

Only one variable can be declared at a time!


3/16/2006 PL/SQL 5 3/16/2006 PL/SQL 6

sepyT ataD dna selbairaV


PL/SQL 3

Character

Boolean Date-Time
3/16/2006

Scalar Data Types

Anchored Data Types


Anchored data types are determined by looking up another objects data type, which could be a column in the database. The anchored declarations have the syntax
<variable-name> <object>%type [not null] [:=<initial-value>] where <object> is another previously declared PL/SQL variable or a database column.

3/16/2006

Anchored Data Types (cont.)


Examples cnum customers.cno%type; cname customers.cname%type; commission real(5,2) :=12.5; x commission%type;

Composite Data Types


PL/SQL provides two composite data types: tables and records. PL/SQL records can be table based, cursor based, or programmer defined. Their declaration syntaxes are:
<record-var-name> <table-name>%rowtype; <record-var-name> <cursor-name>%rowtype; type <type-name> is record (<field1> <datatype1>, <field2> <datatype2>, , <fieldN> <datatypeN>);

3/16/2006

PL/SQL

3/16/2006

PL/SQL

Composite Data Types (cont.)


PL/SQL tables are similar to database tables, except that they always consists of just one column indexed by binary integers. These tables have no bound and grow dynamically much like database tables. The syntax for declaring a PL/SQL table type is:
type <table-type-name> is table of <datatype> index by binary_integer;

Program Control Statements


null statement. It performs no action and Its syntax is null; Assignment statement: it has the syntax:
<variable> := <expression> where the expression on the right side is compatible with the data type of the variable on the left size of the assignment. Examples i := i+1; cname := Jones; sales := price * qty;

3/16/2006

PL/SQL

3/16/2006

PL/SQL

10

Program Control Statements (cont.)


Conditional statements in PL/SQL have 3 variables:
if-then if-then-else if-then-elseif

Program Control Statements (cont.)


Conditional Statements if-then syntax if <condition> then <statement-list> end if; if <condition> then <statement-list-1> else <statement-list-2> end if; if <condition-1> then <statement-list-1> elseif <condition-2> <statement-list-2> elseif <condition-N> <statement-list-N> else <statement-list-N+1> end if;
PL/SQL 12

if-then-else

if-then-elseif

3/16/2006

PL/SQL

11

3/16/2006

3/16/2006

Example
1. if (cnum > 1000) and (cnum < 9000) then i := i+1; dbms_output.put_line(Customer || cnum); end if; 2.
if (cnum > 1000) and (cnum < 9000) then i := i+1; dbms_output.put_line( Valid Customer || cnum); else j := j+1; dbms_output.put_line(Invalid Customer || cnum); end if;

Example (cont.)
3. if (score > 90) then na := na+1; elseif (score > 80) then nb := nb+1; elseif (score > 70) then nc := nc+1; elseif (score > 60) then nd := nd+1; else nf := nf+1; end if;

3/16/2006

PL/SQL

13

3/16/2006

PL/SQL

14

Create the program in a text editor and save it to a file with the extension name as sql. On the Worksheet menu, click run local script.
3/16/2006 PL/SQL 15 3/16/2006 PL/SQL 16

3 kinds of loop control structures: loop, for loop, and while loop
Loop structures syntax

loop

for loop

while loop

3/16/2006

teehskroW sulP*LQS ni margorP LQS/LP a gnitucexE


Loop control structures
loop <statement-list>; end loop; for <loop-counter> in [reverse] <lower>..<upper> loop <statements> ; end loop; while <condition> loop <statement-list>; end loop;
PL/SQL 17

In-class Assignment
Assignment 1

Example Basic Loop


1.
i binary_integer :=0; sum binary_integer :=0; loop i := i+1; if i > 10 then exit; end if; sum := sum + i; end loop

3/16/2006

PL/SQL

18

3/16/2006

Example For Loop


1.
i binary_integer; sum binary_integer :=0; for i in 1 .. 10 loop dmbs_output.put_line( i = || i); sum := sum + i; end loop;

Example While Loop


1.
i := i+1; sum := 0; while (i < 1000) loop sum := sum + i; i := 2 * i; end loop;

2.
for i in reverse 1..5 loop dmbs_output.put_line( i = || i); sum := sum + 2*i; end loop;
3/16/2006 PL/SQL 19 3/16/2006 PL/SQL 20

Program Structure
PL/SQL like many high-level languages, groups its statement into units called blocks. Blocks can be unnamed (anonymous blocks) or named (subprograms) The subprograms can be either functions or procedures.

Anonymous Block
An anonymous block has the following structure declare -- Declaration Section -- Data, subprogram declarations begin -- Executable Section null; -- Program Statements exception -- Exception Section -- Exception handlers when others then null; -- Default handler end;

3/16/2006

PL/SQL

21

3/16/2006

PL/SQL

22

Example
--PL/SQL program to display current date DECLARE today_date DATE; BEGIN today_date := SYSDATE; DBMS_OUTPUT.PUT_LINE('Today''s date is '); DBMS_OUTPUT.PUT_LINE(today_date); END;

In-class Assignment
Assignment 2

3/16/2006

PL/SQL

23

3/16/2006

PL/SQL

24

3/16/2006

Example
declare type customers_table is table of customers%rowtype index by binary_integer; c_table customers_table; cursor c is select cno,cname,street,zip,phone from customers; c_rec c%rowtype; i binary_integer;; begin i := 1; for c_rec in c loop exit when c%notfound; c_table(i) := c_rec; i := i + 1; end loop; for i in 1..c_table.count loop DBMS_OUTPUT.PUT_LINE('c_table(' || i || ').cname = ' || c_table(i).cname);
end loop; end;
3/16/2006 PL/SQL 25 3/16/2006 PL/SQL 26

Execution Script for an Anonymous Block


SQL> start p2 C_table(1).cname = Charles C_table(2).cname=Bertram C_table(3).cname = Barbara PL/SQL procedure successfully completed. SQL> exit

Procedures and Functions


Procedures are declared using the following syntax: procedure <proc-name> [(<parameter>, , <parameter>)] is [<declarations>] begin executable section; [exception exception handlers;] end

Procedures and Functions (cont.)


<proc-name> is the name given to the procedure <parameter> is a parameter with the following syntax <variable-name> [in | out | in out] <datatype> The in, out, and in out parameter types are for input, output, and input/output parameters, respectively <declarations> is the declaration of local variables, constants, and soon. After the executable section, the procedure may end with an optional exception section, as with anonymous blocks.

3/16/2006

PL/SQL

27

3/16/2006

PL/SQL

28

Example
declare cnum customers.cno%type; ccname customers.cname%type; cphone customers.phone%type; ccity zipcodes.city%type; status boolean; procedure get_cust_details(cust_no in customers.cno%type, cust_name out customers.cname%type, cust_phone out customers.phone%type, cust_city out zipcodes.city%type, status out boolean) is begin select cname,phone,city into cust_name,cust_phone,cust_city from customers,zipcodes where customers.zip = zipcodes.zip and customers.cno = cust_no; status := true; exception when no_data_found then status := false; end; //to be continued

Example (cont.)
begin cnum := 1111; get_cust_details(cnum,ccname,cphone,ccity,status); if (status) then DBMS_OUTPUT.PUT_LINE(cnum || ' ' || ccname || ' ' || cphone || ' ' || ccity); else DBMS_OUTPUT.PUT_LINE('Customer ' || cnum || ' not found'); end if; cnum := 5555; get_cust_details(cnum,ccname,cphone,ccity,status); if (status) then DBMS_OUTPUT.PUT_LINE(cnum || ' ' || ccname || ' ' || cphone || ' ' || ccity); else DBMS_OUTPUT.PUT_LINE('Customer ' || cnum || ' not found'); end if; end; /
3/16/2006 PL/SQL 30

3/16/2006

PL/SQL

29

3/16/2006

Procedures and Functions (cont.)


Functions are declared using the following syntax: function <function-name> [(<parameter>, , <parameter>)] return <datatype> is [<declarations>] begin executable section; [exception exception handlers;] end The syntax is almost identical to that of a procedure declaration, except that the function declaration requires the return keyword followed by a data type.
3/16/2006 PL/SQL 31

Example
declare enum customers.cno%type; total number(10,2); status boolean; function total_emp_sales( emp_no in employees.eno%type) return number is sales number; begin select sum(price*qty) into sales from orders,odetails,parts where orders.eno = emp_no and orders.ono = odetails.ono and odetails.pno = parts.pno; return (sales); end; begin enum := 1000; total := total_emp_sales(enum); DBMS_OUTPUT.PUT_LINE('Total sales for employee ' || enum || ' is ' || total); end; /
3/16/2006 PL/SQL 32

Execute a Block
Assume an anonymous block, procedure, or a function is saved in a file file-name.sql In SQL*PLUS, it can be called by the syntax SQL> start file-name In SQL*PLUS Worksheet, on the Worksheet menu, click run local script

Stored Procedures and Functions


Allows for sharing of PL/SQL code by different applications running at different places Use create procedure and create function statements to create the stored procedures and functions

3/16/2006

PL/SQL

33

3/16/2006

PL/SQL

34

Stored Procedures
The syntax for stored procedures is create [or replace] procedure <proc-name> [(<parameter-list>)] as <declarations> begin <executable-section> [exception <exception-section>] end;

Stored Functions
The syntax for stored function is create [or replace] function <func-name> [(<parameter-list>)] return <datatype> as <declarations> begin <executable-section> [exception <exception-section>] end;

3/16/2006

PL/SQL

35

3/16/2006

PL/SQL

36

3/16/2006

Example
create or replace function get_city(cnum in customers.cno%type) return zipcodes.city%type as ccity zipcodes.city%type; begin select into from where city ccity customers,zipcodes cno = cnum and customers.zip = zipcodes.zip; return (ccity); end; /

In-class Assignement
Assignment 6

The following is a call made to the stored function get_city in an SQL query. SQL> select cno, cname, get_city(cno) 2 from customers;

3/16/2006

PL/SQL

37

3/16/2006

PL/SQL

38

Packages
A package is a group of related PL/SQL objects (variables, constants, types, and cursors), procedures, and functions that is stored in the DB. A package definition contains of two parts: the package specification and the package body.

Packages (cont.)
The syntax for creating a package specification is create [or delete] package <package-name> as <PL/SQL declarations>; end;
<PL/SQL declarations> is any set of variable, type, constant, procedure, or function declarations The procedure and function declarations consist only of the name, parameter list, and function return type. They dont contain the actual code since this has to be specified in the package body.

3/16/2006

PL/SQL

39

3/16/2006

PL/SQL

40

Packages (cont.)
The syntax for creating a package body is create [or delete] package body <package-name> as <PL/SQL declarations>; [begin <initialization-code> end;] end;
The <PL/SQL declarations> now contain the code for the functions and procedures defined in the specification. At the end of the body, you can specify an initialization code fragment that initializes variables and other features of the package.
3/16/2006 PL/SQL 41

Example package specification


create or replace package process_orders as procedure add_order_details (onum in odetails.ono%type, pnum in odetails.pno%type, quantity in odetails.qty%type); procedure add_order (onum in orders.ono%type, cnum in orders.cno%type, enum in orders.eno%type, receive in date); procedure ship_order (onum in orders.ono%type, ship in date); end; /

3/16/2006

PL/SQL

42

3/16/2006

Example package body


create or replace package body process_orders as procedure add_order_details (onum in odetails.ono%type, pnum in odetails.pno%type, quantity in odetails.qty%type) is cur_q parts.qoh%type; lev parts.olevel%type; begin select qoh,olevel into cur_q,lev from parts where pno = pnum; if (cur_q > quantity) then update parts set qoh = qoh - quantity where pno = pnum; if (cur_q - quantity) < lev then insert into restock values (sysdate,pnum); end if; insert into odetails values (onum,pnum,quantity); else insert into odetails_errors values(sysdate,onum,pnum,'Do not have enough to sell'); end if; exception when others then rollback work; insert into odetails_errors values(sysdate,onum,pnum,'error inserting order detail'); end; //to be continued
3/16/2006 PL/SQL 43

Example package body (cont.)


procedure add_order (onum IN orders.ono%type, cnum IN orders.cno%type, enum IN orders.eno%type, receive IN date) is begin if (receive is null) then insert into orders values (onum,cnum,enum,sysdate,null); else insert into orders values (onum,cnum,enum,receive,null); end if; exception when others then rollback work; insert into orders_errors values(sysdate,onum,'error inserting order'); end; //to be continued

3/16/2006

PL/SQL

44

Example package body (cont.)


procedure ship_order (onum IN orders.ono%type, ship IN date) is begin if (ship is null) then update orders set shipped = sysdate where ono = onum; else update orders set shipped = ship where ono = onum; end if; exception when others then rollback work; insert into orders_errors values(sysdate,onum,'error updating shipped date'); end; end; /
3/16/2006 PL/SQL 45

Exercise
Execute the following commnads agains the mail-order database in SQL*Plus.
SQL> execute process_orders.add_order(2000, 111, 1000, null); SQL> execute process_orders.add_order_details (2000, 10509, 50); SQL> execute process_orders.add_order_details (2000, 10701, 200); SQL> execute process_orders.ship_order(2000,29-JAN-98); SQL> execute process_orders.add_order(2001,1234,1000,null); SQL> execute process_orders.add_order_details (2000, 10999, 5);

3/16/2006

PL/SQL

46

Das könnte Ihnen auch gefallen