Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Semestr2 / 1 - Oracle / PL_SQL / b14261.pdf
Скачиваний:
27
Добавлен:
12.05.2015
Размер:
4.36 Mб
Скачать

Assigning Values to Variables

the_ratio NUMBER; BEGIN

<<inner_label>> <<another_label>>

DECLARE

denominator NUMBER := 0; BEGIN

--first use the denominator value = 7 from global DECLARE

--to compute a rough value of pi

the_ratio := numerator/compute_ratio.denominator; DBMS_OUTPUT.PUT_LINE('Ratio = ' || the_ratio);

--now use the local denominator value = 0 to raise an exception

--inner_label is not needed but used for clarification

the_ratio := numerator/inner_label.denominator; DBMS_OUTPUT.PUT_LINE('Ratio = ' || the_ratio);

--if you use a duplicate label, you might get errors

--or unpredictable results

the_ratio := numerator/another_label.denominator; DBMS_OUTPUT.PUT_LINE('Ratio = ' || the_ratio);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Divide-by-zero error: can''t divide ' || numerator || ' by ' || denominator);

WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Unexpected error.');

END inner_label; END compute_ratio;

/

Assigning Values to Variables

You can use assignment statements to assign values to variables. For example, the following statement assigns a new value to the variable bonus, overwriting its old value:

bonus := salary * 0.15;

Variables and constants are initialized every time a block or subprogram is entered. By default, variables are initialized to NULL. Unless you expressly initialize a variable, its value is undefined (NULL) as shown in Example 2–20.

Example 2–20 Initialization of Variables and Constants

DECLARE

counter INTEGER; BEGIN

--COUNTER is initially NULL, so 'COUNTER + 1' is also null. counter := counter + 1;

IF counter IS NULL THEN DBMS_OUTPUT.PUT_LINE('COUNTER is NULL not 1.');

END IF; END;

/

To avoid unexpected results, never reference a variable before you assign it a value. The expression following the assignment operator can be arbitrarily complex, but it must yield a datatype that is the same as or convertible to the datatype of the variable.

2-18 Oracle Database PL/SQL User’s Guide and Reference

Соседние файлы в папке PL_SQL