Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
29
Добавлен:
16.04.2013
Размер:
5.97 Mб
Скачать

Declarations

END IF;

/*

The following line computes the area of a circle using pi, which is the ratio between the circumference and diameter.

*/

area := pi * radius**2; END;

/

You can use multi-line comment delimiters to comment-out whole sections of code:

/* LOOP

FETCH c1 INTO emp_rec; EXIT WHEN c1%NOTFOUND;

...

END LOOP; */

Restrictions on Comments

You cannot nest comments.

You cannot use single-line comments in a PL/SQL block that will be processed by an Oracle Precompiler program because end-of-line characters are ignored. As a result, single-line comments extend to the end of the block, not just to the end of a line. In this case, use the /* */ notation instead.

Declarations

Your program stores values in variables and constants. As the program executes, the values of variables can change, but the values of constants cannot.

You can declare variables and constants in the declarative part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value, specify its datatype, and name the storage location so that you can reference it.

A couple of examples follow:

DECLARE

birthday DATE; emp_count SMALLINT := 0;

The first declaration names a variable of type DATE. The second declaration names a variable of type SMALLINT and uses the assignment operator to assign an initial value of zero to the variable.

The next examples show that the expression following the assignment operator can be arbitrarily complex and can refer to previously initialized variables:

DECLARE

 

pi

REAL := 3.14159;

radius

REAL := 1;

area

REAL := pi * radius**2;

BEGIN

 

NULL;

 

END;

 

/

 

2-8 PL/SQL User's Guide and Reference

Declarations

By default, variables are initialized to NULL, so it is redundant to include ":= NULL" in a variable declaration.

To declare a constant, put the keyword CONSTANT before the type specifier:

DECLARE

credit_limit CONSTANT REAL := 5000.00; max_days_in_year CONSTANT INTEGER := 366; urban_legend CONSTANT BOOLEAN := FALSE;

BEGIN NULL;

END;

/

This declaration names a constant of type REAL and assigns an unchangeable value of 5000 to the constant. A constant must be initialized in its declaration. Otherwise, you get a compilation error.

Using DEFAULT

You can use the keyword DEFAULT instead of the assignment operator to initialize variables. For example, the declaration

blood_type CHAR := 'O';

can be rewritten as follows:

blood_type CHAR DEFAULT 'O';

Use DEFAULT for variables that have a typical value. Use the assignment operator for variables (such as counters and accumulators) that have no typical value. For example:

hours_worked INTEGER DEFAULT 40; employee_count INTEGER := 0;

You can also use DEFAULT to initialize subprogram parameters, cursor parameters, and fields in a user-defined record.

Using NOT NULL

Besides assigning an initial value, declarations can impose the NOT NULL constraint:

DECLARE

acct_id INTEGER(4) NOT NULL := 9999;

You cannot assign nulls to a variable defined as NOT NULL. If you try, PL/SQL raises the predefined exception VALUE_ERROR.

The NOT NULL constraint must be followed by an initialization clause.

PL/SQL provide subtypes NATURALN and POSITIVEN that are predefined as NOT NULL. You can omit the NOT NULL constraint when declaring variables of these types, and you must include an initialization clause.

Using the %TYPE Attribute

The %TYPE attribute provides the datatype of a variable or database column. In the following example, %TYPE provides the datatype of a variable:

DECLARE

credit NUMBER(7,2); debit credit%TYPE;

Fundamentals of the PL/SQL Language 2-9

Declarations

name VARCHAR2(20) := 'JoHn SmItH';

--If we increase the length of NAME, the other variables

--become longer too.

upper_name name%TYPE := UPPER(name); lower_name name%TYPE := LOWER(name);

init_name name%TYPE := INITCAP(name); BEGIN

NULL;

END;

/

Variables declared using %TYPE are treated like those declared using a datatype specifier. For example, given the previous declarations, PL/SQL treats debit like a REAL(7,2) variable. A %TYPE declaration can also include an initialization clause.

The %TYPE attribute is particularly useful when declaring variables that refer to database columns. You can reference a table and column, or you can reference an owner, table, and column, as in

DECLARE

--If the length of the column ever changes, this code

--will use the new length automatically. the_trigger user_triggers.trigger_name%TYPE;

BEGIN NULL;

END;

/

When you use table_name.column_name.TYPE to declare a variable, you do not need to know the actual datatype, and attributes such as precision, scale, and length. If the database definition of the column changes, the datatype of the variable changes accordingly at run time.

%TYPE variables do not inherit the NOT NULL column constraint. In the next example, even though the database column employee_id is defined as NOT NULL, you can assign a null to the variable my_empno:

DECLARE

my_empno employees.employee_id%TYPE; BEGIN

my_empno := NULL; -- this works END;

/

Using the %ROWTYPE Attribute

The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record can store an entire row of data selected from the table, or fetched from a cursor or strongly typed cursor variable:

DECLARE

--%ROWTYPE can include all the columns in a table...

emp_rec employees%ROWTYPE;

--...or a subset of the columns, based on a cursor. CURSOR c1 IS

SELECT department_id, department_name FROM departments; dept_rec c1%ROWTYPE;

--Could even make a %ROWTYPE with columns from multiple tables. CURSOR c2 IS

SELECT employee_id, email, employees.manager_id, location_id

2-10 PL/SQL User's Guide and Reference

Declarations

FROM employees, departments

WHERE employees.department_id = departments.department_id; join_rec c2%ROWTYPE;

BEGIN

--We know EMP_REC can hold a row from the EMPLOYEES table. SELECT * INTO emp_rec FROM employees WHERE ROWNUM < 2;

--We can refer to the fields of EMP_REC using column names

--from the EMPLOYEES table.

IF emp_rec.department_id = 20 AND emp_rec.last_name = 'JOHNSON' THEN

emp_rec.salary := emp_rec.salary * 1.15; END IF;

END;

/

Columns in a row and corresponding fields in a record have the same names and datatypes. However, fields in a %ROWTYPE record do not inherit the NOT NULL column constraint.

Aggregate Assignment

Although a %ROWTYPE declaration cannot include an initialization clause, there are ways to assign values to all fields in a record at once. You can assign one record to another if their declarations refer to the same table or cursor. For example, the following assignment is allowed:

DECLARE

dept_rec1 departments%ROWTYPE; dept_rec2 departments%ROWTYPE;

CURSOR c1 IS SELECT department_id, location_id FROM departments; dept_rec3 c1%ROWTYPE;

BEGIN

dept_rec1 := dept_rec2; -- allowed

--dept_rec2 refers to a table, dept_rec3 refers to a cursor

--dept_rec2 := dept_rec3; -- not allowed

END;

/

You can assign a list of column values to a record by using the SELECT or FETCH statement, as the following example shows. The column names must appear in the order in which they were defined by the CREATE TABLE or CREATE VIEW statement.

DECLARE

dept_rec departments%ROWTYPE; BEGIN

SELECT * INTO dept_rec FROM departments WHERE department_id = 30 and ROWNUM < 2;

END;

/

However, there is no constructor for a record type, so you cannot assign a list of column values to a record by using an assignment statement.

Using Aliases

Select-list items fetched from a cursor associated with %ROWTYPE must have simple names or, if they are expressions, must have aliases. The following example uses an alias called complete_name to represent the concatenation of two columns:

BEGIN

--We assign an alias (COMPLETE_NAME) to the expression value, because

--it has no column name.

Fundamentals of the PL/SQL Language 2-11

Соседние файлы в папке Oracle 10g