Control structures are probably the most useful (and important) part of PL/oraSQL. With PL/oraSQL's control structures, you can manipulate LightDB data in a very flexible and powerful way.
There is one command available that allow you to return data
from a function: RETURN
.
RETURN
RETURN expression
;
RETURN
with an expression terminates the
function and returns the value of
expression
to the caller. This form
is used for PL/oraSQL functions that do
not return a set.
If you declared the function with output parameters, write just
RETURN
with no expression. The current values
of the output parameter variables will be returned. Currently,
mixed use of oracle output parameters and return clauses is not supported.
The return value of a function cannot be left undefined. If
control reaches the end of the top-level block of the function
without hitting a RETURN
statement, a run-time
error will occur. In those cases a RETURN
statement is
automatically executed if the top-level block finishes.
Some examples:
-- functions returning a scalar type RETURN 1 + 2; RETURN scalar_var;
A procedure does not have a return value. A procedure can therefore end
without a RETURN
statement. If you wish to use
a RETURN
statement to exit the code early, write
just RETURN
with no expression.
If the procedure has output parameters, the final values of the output parameter variables will be returned to the caller.
A PL/oraSQL function, procedure,
or Anonymous
block can call a procedure. For example:
CREATE PROCEDURE triple(x in int, y out int) AS BEGIN y := x * 3; END; / DECLARE myvar int := 5; myresult int := 10; BEGIN triple(myvar, myresult); DBMS_OUTPUT.PUT_LINE('myresult = '||myresult); -- prints 15 END; /
IF
and CASE
statements let you execute
alternative commands based on certain conditions.
PL/oraSQL has three forms of IF
:
IF ... THEN ... END IF
IF ... THEN ... ELSE ... END IF
IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF
and two forms of CASE
:
CASE ... WHEN ... THEN ... ELSE ... END CASE
CASE WHEN ... THEN ... ELSE ... END CASE
IF-THEN
IFboolean-expression
THENstatements
END IF;
IF-THEN
statements are the simplest form of
IF
. The statements between
THEN
and END IF
will be
executed if the condition is true. Otherwise, they are
skipped.
Example:
IF v_user_id <> 0 THEN UPDATE users SET email = v_email WHERE user_id = v_user_id; END IF;
IF-THEN-ELSE
IFboolean-expression
THENstatements
ELSEstatements
END IF;
IF-THEN-ELSE
statements add to
IF-THEN
by letting you specify an
alternative set of statements that should be executed if the
condition is not true. (Note this includes the case where the
condition evaluates to NULL.)
Examples:
IF parentid IS NULL OR parentid = '' THEN RETURN fullname; ELSE RETURN hp_true_filename(parentid) || '/' || fullname; END IF;
IF v_count > 0 THEN INSERT INTO users_count (count) VALUES (v_count); RETURN 't'; ELSE RETURN 'f'; END IF;
IF-THEN-ELSIF
IFboolean-expression
THENstatements
[ ELSIFboolean-expression
THENstatements
] [ ELSIFboolean-expression
THENstatements
... ] [ ELSEstatements
] END IF;
Sometimes there are more than just two alternatives.
IF-THEN-ELSIF
provides a convenient
method of checking several alternatives in turn.
The IF
conditions are tested successively
until the first one that is true is found. Then the
associated statement(s) are executed, after which control
passes to the next statement after END IF
.
(Any subsequent IF
conditions are not
tested.) If none of the IF
conditions is true,
then the ELSE
block (if any) is executed.
Here is an example:
IF number = 0 THEN result := 'zero'; ELSIF number > 0 THEN result := 'positive'; ELSIF number < 0 THEN result := 'negative'; ELSE -- hmm, the only other possibility is that number is null result := 'NULL'; END IF;
The key word ELSIF
can also be spelled
ELSEIF
.
An alternative way of accomplishing the same task is to nest
IF-THEN-ELSE
statements, as in the
following example:
IF demo_row.sex = 'm' THEN pretty_sex := 'man'; ELSE IF demo_row.sex = 'f' THEN pretty_sex := 'woman'; END IF; END IF;
However, this method requires writing a matching END IF
for each IF
, so it is much more cumbersome than
using ELSIF
when there are many alternatives.
CASE
CASEsearch-expression
WHENexpression
[,expression
[ ... ]] THENstatements
[ WHENexpression
[,expression
[ ... ]] THENstatements
... ] [ ELSEstatements
] END CASE;
The simple form of CASE
provides conditional execution
based on equality of operands. The search-expression
is evaluated (once) and successively compared to each
expression
in the WHEN
clauses.
If a match is found, then the corresponding
statements
are executed, and then control
passes to the next statement after END CASE
. (Subsequent
WHEN
expressions are not evaluated.) If no match is
found, the ELSE
statements
are
executed; but if ELSE
is not present, then a
CASE_NOT_FOUND
exception is raised.
Here is a simple example:
CASE x WHEN 1, 2 THEN msg := 'one or two'; ELSE msg := 'other value than one or two'; END CASE;
CASE
CASE WHENboolean-expression
THENstatements
[ WHENboolean-expression
THENstatements
... ] [ ELSEstatements
] END CASE;
The searched form of CASE
provides conditional execution
based on truth of Boolean expressions. Each WHEN
clause's
boolean-expression
is evaluated in turn,
until one is found that yields true
. Then the
corresponding statements
are executed, and
then control passes to the next statement after END CASE
.
(Subsequent WHEN
expressions are not evaluated.)
If no true result is found, the ELSE
statements
are executed;
but if ELSE
is not present, then a
CASE_NOT_FOUND
exception is raised.
Here is an example:
CASE WHEN x BETWEEN 0 AND 10 THEN msg := 'value is between zero and ten'; WHEN x BETWEEN 11 AND 20 THEN msg := 'value is between eleven and twenty'; END CASE;
This form of CASE
is entirely equivalent to
IF-THEN-ELSIF
, except for the rule that reaching
an omitted ELSE
clause results in an error rather
than doing nothing.
With the LOOP
, EXIT
,
CONTINUE
, WHILE
, FOR
,
and FOREACH
statements, you can arrange for your
PL/oraSQL function to repeat a series of commands.
LOOP
[ <<label
>> ] LOOPstatements
END LOOP [label
];
LOOP
defines an unconditional loop that is repeated
indefinitely until terminated by an EXIT
or
RETURN
statement. The optional
label
can be used by EXIT
and CONTINUE
statements within nested loops to
specify which loop those statements refer to.
Label name cannot be the unreserved keyword label
.
EXIT
EXIT [label
] [ WHENboolean-expression
];
If no label
is given, the innermost
loop is terminated and the statement following END
LOOP
is executed next. If label
is given, it must be the label of the current or some outer
level of nested loop or block. Then the named loop or block is
terminated and control continues with the statement after the
loop's/block's corresponding END
.
If WHEN
is specified, the loop exit occurs only if
boolean-expression
is true. Otherwise, control passes
to the statement after EXIT
.
EXIT
can be used with all types of loops; it is
not limited to use with unconditional loops.
Examples:
LOOP -- some computations IF count > 0 THEN EXIT; -- exit loop END IF; END LOOP; LOOP -- some computations EXIT WHEN count > 0; -- same result as previous example END LOOP;
CONTINUE
CONTINUE [label
] [ WHENboolean-expression
];
If no label
is given, the next iteration of
the innermost loop is begun. That is, all statements remaining
in the loop body are skipped, and control returns
to the loop control expression (if any) to determine whether
another loop iteration is needed.
If label
is present, it
specifies the label of the loop whose execution will be
continued.
If WHEN
is specified, the next iteration of the
loop is begun only if boolean-expression
is
true. Otherwise, control passes to the statement after
CONTINUE
.
CONTINUE
can be used with all types of loops; it
is not limited to use with unconditional loops.
Examples:
LOOP -- some computations EXIT WHEN count > 100; CONTINUE WHEN count < 50; -- some computations for count IN [50 .. 100] END LOOP;
WHILE
[ <<label
>> ] WHILEboolean-expression
LOOPstatements
END LOOP [label
];
The WHILE
statement repeats a
sequence of statements so long as the
boolean-expression
evaluates to true. The expression is checked just before
each entry to the loop body.
For example:
WHILE amount_owed > 0 AND gift_certificate_balance > 0 LOOP -- some computations here END LOOP; WHILE NOT done LOOP -- some computations here END LOOP;
FOR
(Integer Variant)[ <<label
>> ] FORname
IN [ REVERSE ]expression
..expression
[ BYexpression
] LOOPstatements
END LOOP [label
];
This form of FOR
creates a loop that iterates over a range
of integer values. The variable
name
is automatically defined as type
integer
and exists only inside the loop (any existing
definition of the variable name is ignored within the loop).
The two expressions giving
the lower and upper bound of the range are evaluated once when entering
the loop. If the BY
clause isn't specified the iteration
step is 1, otherwise it's the value specified in the BY
clause, which again is evaluated once on loop entry.
If REVERSE
is specified then the step value is
subtracted, rather than added, after each iteration.
Some examples of integer FOR
loops:
FOR i IN 1..10 LOOP -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop END LOOP; FOR i IN REVERSE 10..1 LOOP -- i will take on the values 10,9,8,7,6,5,4,3,2,1 within the loop END LOOP; FOR i IN REVERSE 10..1 BY 2 LOOP -- i will take on the values 10,8,6,4,2 within the loop END LOOP;
If the lower bound is greater than the upper bound (or less than,
in the REVERSE
case), the loop body is not
executed at all. No error is raised.
If a label
is attached to the
FOR
loop then the integer loop variable can be
referenced with a qualified name, using that
label
.
Using a different type of FOR
loop, you can iterate through
the results of a query and manipulate that data
accordingly. The syntax is:
[ <<label
>> ] FORtarget
INquery
LOOPstatements
END LOOP [label
];
The target
is a record variable, row variable,
or comma-separated list of scalar variables.
The target
is successively assigned each row
resulting from the query
and the loop body is
executed for each row. Here is an example:
create table refresh_mview (mv_schema varchar(100), mv_name varchar(100), owner varchar(100)); insert into refresh_mview values ('asd', 'sdf', 'dfg'); CREATE OR REPLACE FUNCTION refresh_mviews(id int) RETURN integer IS BEGIN DBMS_OUTPUT.PUT_LINE('Refreshing all materialized views...'); FOR mviews IN (SELECT mv_schema, mv_name, owner FROM refresh_mview) LOOP -- Now "mviews" has one record with information about the materialized view DBMS_OUTPUT.PUT_LINE('Refreshing materialized view '|| mviews.mv_schema||'.'|| mviews.mv_name|| ' (owner: %)...'|| mviews.owner); END LOOP; DBMS_OUTPUT.PUT_LINE('Done refreshing materialized views.'); RETURN id; END; /
If the loop is terminated by an EXIT
statement, the last
assigned row value is still accessible after the loop.
The query
used in this type of FOR
statement can be any SQL command that returns rows to the caller:
SELECT
is the most common case,
but you can also use INSERT
, UPDATE
, or
DELETE
with a RETURNING
clause. Some utility
commands such as EXPLAIN
will work too.
PL/oraSQL variables are substituted into the query text, and the query plan is cached for possible re-use.
The FOR-IN-EXECUTE-IMMEDIATE
statement is another way to iterate over
rows:
[ <<label
>> ] FORtarget
IN EXECUTE IMMEDIATEtext_expression
[ USINGexpression
[, ... ] ] LOOPstatements
END LOOP [label
];
This is like the previous form, except that the source query
is specified as a string expression, which is evaluated and replanned
on each entry to the FOR
loop. This allows the programmer to
choose the speed of a preplanned query or the flexibility of a dynamic
query, just as with a plain EXECUTE IMMEDIATE
statement.
As with EXECUTE IMMEDIATE
, parameter values can be inserted
into the dynamic command via USING
.
Another way to specify the query whose results should be iterated through is to declare it as a cursor. This is described in Section 42.7.3.2.
By default, any error occurring in a PL/oraSQL
function aborts execution of the function and the
surrounding transaction. You can trap errors and recover
from them by using a BEGIN
block with an
EXCEPTION
clause. The syntax is an extension of the
normal syntax for a BEGIN
block:
[ DECLAREdeclarations
] BEGINstatements
EXCEPTION WHENcondition
[ ORcondition
... ] THENhandler_statements
[ WHENcondition
[ ORcondition
... ] THENhandler_statements
... ] END; /
If no error occurs, this form of block simply executes all the
statements
, and then control passes
to the next statement after END
. But if an error
occurs within the statements
, further
processing of the statements
is
abandoned, and control passes to the EXCEPTION
list.
The list is searched for the first condition
matching the error that occurred. If a match is found, the
corresponding handler_statements
are
executed, and then control passes to the next statement after
END
. If no match is found, the error propagates out
as though the EXCEPTION
clause were not there at all:
the error can be caught by an enclosing block with
EXCEPTION
, or if there is none it aborts processing
of the function.
The special condition name OTHERS
matches every error type.
Condition names are not case-sensitive.
A block containing an EXCEPTION
clause is significantly
more expensive to enter and exit than a block without one. Therefore,
don't use EXCEPTION
without need.