Docsity

Executing PL/SQL Programs: Examples and Best Practices, Slides of English

Partial preview of the text

Download Executing PL/SQL Programs: Examples and Best Practices and more Slides English in PDF only on Docsity!

Basics of PL/SQL

Writing Your First Program

A SIMPLE PL/SQL CODE BLOCK THAT

DISPLAYS THE WORD HELLO

SQL> set serveroutput on

SQL> begin

2 dbms_output.put_line ('Hello');

3 end;

Hello

PL/SQL procedure successfully completed.

SQL>

End listing

”. Some important features of the program are:

  • The executable portion of a PL/SQL code block starts with the keyword Begin

and is terminated with the keyword End.

  • PL/SQL code blocks are comprised of statements. Each statement ends with a

semi-colon.

  • PL/SQL code blocks are followed by a slash (/) in the first position of the

following line. This causes the code block statements to be executed.

  • The only PL/SQL code block keyword that is followed by a semi-colon is the

End keyword.

Executing the PL/SQL Program

Executing a PL/SQL Program

SQL> START

C:\BUSINESS\ORACLE~1\PLSQL1\L1.SQL

HELLO

PL/SQL PROCEDURE SUCCESSFULLY

COMPLETED

End listing

The code block is terminated by the End keyword. This is the only keyword within the

construct that is followed by a semi-colon (;). The only required section is the executable

section. This means the code block must have the Begin and End keywords. The code

block is executed by the slash (/) symbol.

Executing a PL/SQL Program

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

2 LOCAL_VARIABLE VARCHAR2(30);

3 BEGIN

4 SELECT 'NUMBER OF

EMPLOYEES'||TO_CHAR(COUNT(LAST_NAME),

5 INTO LOCAL_VARIABLE

6 FROM EMPLOYEE;

7 DBMS_OUTPUT.PUT_LINE

(LOCAL_VARIABLE);

8 EXCEPTION

9 WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('ERROR

OCCURED');

10 END;

NUMBER OF EMPLOYEES 19

PL/SQL PROCEDURE SUCCESSFULLY

COMPLETED.

End Listing

Block Labels, Labels, and the Goto Keyword

Some rules to remember are:

  • Labels are defined by placing two less than ( << ) symbols before the label name

and two greater than ( >> ) symbols after the label name.

  • The Goto keyword is used to redirect the focus of the code block. The name of

the label is placed after the Goto keyword.

A Block label is similar to a label except that it can be used to qualify the contents of a

block. The Block label is placed at the beginning of the block. The label is then placed

following the End keyword. By placing the label definition and the end label, you can

identify the code block and the variables within the labeled block. This can be a useful

device when the program contains multiple code blocks.

A Block Label, Label, and Goto Command

SQL> BEGIN <<B_LABEL>> 2 GOTO MIDDLE; 3 <> 4 DBMS_OUTPUT.PUT_LINE ('TOP STATEMENT'); 5 GOTO BOTTOM; 6 <> 7 DBMS_OUTPUT.PUT_LINE ('MIDDLE STATEMENT'); 8 GOTO TOP; 9 <> 10 DBMS_OUTPUT.PUT_LINE ('BOTTOM STATEMENT'); 11 END B_LABEL; 12 / MIDDLE STATEMENT TOP STATEMENT BOTTOM STATEMENT

PL/SQL PROCEDURE SUCCESSFULLY

COMPLETED.

SQL>

End listing

DECLARING VARIABLES AND ASSIGNING VALUES

Defining Variables

Variables are defined in the declaration section of the program. The syntax is:

Variable_name datatype(precision);

Oracle treats a variable definition similar to other statements. The definition must end with a semi-colon. The definition statement begins with the variable name and contains the data type. These are the mandatory parts of the definition. A value may also be assigned to the variable during the definition statement. The variable may also be constrained.

Character Definitions

The following are examples of definitions:

first_name varchar2(15);

social_security_number char(11);

The PL/SQL maximum length of the char and varchar2 data types is larger than the

length allowed in the Oracle database.

Numeric Definitions

Numeric data definitions can include two parameters. The first parameter is precision

and the second is scale. Precision defines the overall length of the value. Scale

determines the number of digits to the left or right of the decimal point. The range of

scale is –84 to 127.

If a scale is specified, rounding will occur at the end. The following rules apply:

  • Positive scale definitions cause rounding to the right of the decimal point.
  • Negative scale definitions cause rounding to the left of the decimal point.
  • Zero scale definitions cause rounding to the nearest whole number.

The default precision of a number is 38.

age integer(3); gallons number(3);

salary number(8,2);

Aggregate and PL/SQL Record Definitions

An aggregate variable definition is based upon a database or PL/SQL object. They

consist of one or more variables and are extremely useful. They have two advantages:

  1. The developer can automatically define a variable with the same data specifications as a table column or cursor variable without actually knowing the specifications.
  2. The developer can set up an array of variables for a cursor or table record with one statement. The variables will have the same specifications as the table or cursor variables.

Variable_name table_cursor_name.column_name%type;

lname employee.last_name%type;

Array_name table/cursor_name%rowtype;

Dept_var department%rowtype;

Dept_var.department

Dept_var.department_name

Assigning Values to Variables

A PL/SQL procedure would not be useful unless there is a way to populate the variables

with a value. Fortunately, PL/SQL gives us two ways to accomplish this. These are:

  • := - The colon/equal sign assigns the argument on the left of the

operator to the argument or variable on the right of the sign.

  • Into - The Into keyword is used in a Select or Fetch statement. When

used in a Select statement, it assigns the values in the Select

clause to the variables following the Into keyword. When used

with the Fetch statement, it assigns the cursor values to the

variables that follow the Into keyword.

Practice

3. Create a PL/SQL procedure that computes the retirement age of the youngest

employee. You should also list the employee’s name.

4. Modify the program in #3 to compute the number of days between today and the

employee’s retirement date.

5. Identify the number of tool purchases for Harry Truman and George Bush.

Output the name of the employee with the greater number of tool purchases.

THE IF-THEN-ELSE STRUCTURE

To be effective, a code block or procedure needs to have commands that allow the

developer to document the logic necessary to determine the behavior. Oracle uses

conditional logic statements to form the procedure’s behavior. The logic statements

come in two forms. These are:

If-then-else structures

Elsif statements

The If-Then-Else Structure

The basic structure is as follows:

If ( conditional expression ) then

Statements;

Else

Statements;

End if;

An If-Then-Else Structure Example

SQL> declare 2 male_avg number; 3 female_avg number; 4 begin 5 select avg(months_between(employment_date, birth_date)/12) 6 into male_avg 7 from employee 8 where gender = 'M'; 9 select avg(months_between(employment_date, birth_date)/12) 10 into female_avg 11 from employee 12 where gender = 'F'; 13 if (male_avg > female_avg) then 14 dbms_output.put_line ('Males have the greatest avg hiring age'); 15 dbms_output.put_line ('With and avg age of '||to_char(male_avg)); 16 else 17 dbms_output.put_line ('Females have the greatest avg hiring age'); 18 dbms_output.put_line ('With and avg age of '||to_char(female_avg)); 19 end if; 20 end; 21 / Males have the greatest avg hiring age With and avg age of 55.

PL/SQL procedure successfully completed.

SQL>

End Listing

Practice

  1. Use a nested-if statement to output whether the highest employee in #5 had two or more than the lower.
  2. Output which decade of the twentieth century Bill Clinton was born in.
  3. Create a PL/SQL procedure that computes and displays the average starting age of the set of employees in the Employee database.

CURSORS

A cursor is a device that is used to retrieve a set of records from a table/view into

memory. Cursors allow each of the records to be read into the code block and processed

one-at-a-time. A cursor can be compared to a book containing a page mark. Each of the

pages is a record in the set of records retrieved when the cursor is executed. The

bookmark indicates the current page. When using a cursor , Oracle always knows the

current record. As one record is read into the code block , the current record is changed

just as the bookmark is changed as a page is read. Cursors are important tools for the

processing of records. They allow the developer to bring records into the code block and

to process them using a complex set of statements

Declaring the Cursor

Cursors are defined in the Declaration section of the code block. The definition consists

of the keywords Cursor and Is, the name of the cursor, and the Select statement used to

retrieve the record set. The following is an example of the cursor definition structure:

Cursor cusor name is select statement;

Cursor Commands

There are three commands that are used in conjunction with cursors. These commands

are contained in Table:

Cursor Commands

Command Example Description

Open Open cursor_name; This command executes the

cursor’s Select statement and

places the records into

memory. The first record in

the set is the current set.

Fetch/into Fetch cursor_name into variables; This command assigns the

values from the current cursor

record to the listed local

variables or PL/SQL record.

It also makes the next record

in the set the current record.

Close Close cursor_name; Terminates the cursor and

frees the memory used by the

cursor for other uses.

Using Aggregate Variables With Cursors

In the previous example local variables were defined for each of the columns retrieved by

the cursors. The developer had to declare each of the variables used to assign cursor

values and also had to include them in the fetch statements. There are two potential

problems with this method. These are:

  1. The developer must document the local variable’s size and type. If the size of the cursor variable is larger than the size of the local variable its value is assigned to, an error will occur and the procedure will terminate. The procedure will also terminate if the data types are different.
  2. If the size of the column is changed, the procedure variables will also need to be changed. Failure to change the procedure may cause the procedure to terminate when run.

Using %rowtype to Define Cursor Variables

SQL> declare 2 cursor find_old_b_day is select min(birth_date) day 3 from employee; 4 old_date find_old_b_day%rowtype; 5 cursor id_employee is select last_name, first_name 6 from employee 7 where birth_date = old_date.day; 8 id id_employee%rowtype; 9 begin 10 open find_old_b_day; 11 fetch find_old_b_day into old_date; 12 close find_old_b_day; 13 open id_employee; 14 fetch id_employee into id; 15 close id_employee; 16 dbms_output.put_line ('The Oldest Employee Is ' 17 ||id.last_name||', '||id.first_name); 18 end; 19 / The Oldest Employee Is JOHNSON, ANDREW

PL/SQL procedure successfully completed.

SQL>

End Listing

PL/SQL

records

PL/SQL

record variable

Several things to remember when using %rowtype are:

  • The cursor must be defined before the PL/SQL record definition.
  • All cursor columns must have a name. When expressions are included such as

the case of group functions, you must include a column alias.

Practice

  1. Create a PL/SQL procedure that computes the hiring age of the first employee hired by the “WEL” department.