BEGIN ... END statement

The BEGIN ... END statement gives the statements defined within the BEGIN and END keywords the status of a single statement.

This allows the statements to become the body of a function or a procedure.

Syntax

The second Label can be present only if the first Label is present, and the labels must be identical. Two or more labelled statements at the same level can have the same Label, but this partly negates the advantage of the second Label. The advantage is that the labels unambiguously and accurately match each END with its BEGIN. However, a labelled statement within statements cannot have the same Label, because this makes the behavior of the ITERATE and LEAVE statements ambiguous.

You can consider the BEGIN ... END statement to be a looping construct, which always loops just once. The effect of an ITERATE or LEAVE within a BEGIN ... END statement is the same; control is transferred to the statement following the END. Using ITERATE or LEAVE within a BEGIN ... END statement is useful in cases where there is a long series of computations that needs to be abandoned, either because a definite result has been achieved or because an error has occurred.

A new local variable scope is opened immediately after the opening BEGIN and, therefore, any variables declared within this statement go out of scope when the terminating END is reached. If a local variable has the same name as an existing variable, any references to that name that occur after the declaration access the local variable. For example:
DECLARE Variable1 CHAR 'Existing variable';

-- A reference to Variable1 here returns 'Existing variable'

BEGIN
  -- A reference to Variable1 here returns 'Existing variable'

  DECLARE Variable1 CHAR 'Local variable';  -- Perfectly legal even though 
the name is the same

  -- A reference to Variable1 here returns 'Local variable'
END;

Related concepts
ESQL

Related tasks
Developing ESQL

Related reference
Syntax preference
ESQL statements