BEGIN ... END

Top  Previous  Next

You can group statements within a block and add exception handling.

 

Syntax

<block> ::=

  BEGIN

    [<compound_statement> ...]

    [<when_do> ...]

  END

 

<compound_statement> ::= {<block> | <statement>}

 

See Also

WHEN ... DO

 

A BEGIN ... END block wraps zero or more statements together as a unit of code. Each block starts with BEGIN and is finished by the END, there's no need to terminate this statement with the semicolon ";" character. Blocks can be nested.

 

Each block can have its own exception handling via the WHEN ... DO clause, whenever an exception occurs, the statements in this block are undone and an exception handler is executed. If there's no exception handler available, the exception is escalated to the parent block.

 

The final END of a scripting block or subroutine terminates that block of code and will return control to the caller.

 

Examples

This example is taken from the Firebird example database, it was originally a stored procedure.

 

There's two BEGIN ... END blocks, one is the main block and there's a 2nd block for the FOR ... DO loop. The looping code consists of two statements, so there's a block to execute them both in the DO-part of the loop.

 

EXECUTE UDSBLOCK ( DNO CHAR(3) )

RETURNS (

  TOT DECIMAL(12,2))

AS

  DECLARE VARIABLE SUMB DECIMAL(12,2);

  DECLARE VARIABLE RDNO CHAR(3);

  DECLARE VARIABLE CNT  INTEGER;

BEGIN

  TOT = 0;

 

  SELECT BUDGET

  FROM DEPARTMENT

  WHERE DEPT_NO = :DNO

  INTO :TOT;

 

  SELECT COUNT(BUDGET)

  FROM DEPARTMENT

  WHERE HEAD_DEPT = :DNO

  INTO :CNT;

 

  IF (CNT = 0) THEN

    SUSPEND;

 

  FOR SELECT DEPT_NO

    FROM DEPARTMENT

    WHERE HEAD_DEPT = :DNO

    INTO :RDNO

  DO

  BEGIN

    EXECUTE PROCEDURE DEPT_BUDGET(:RDNO)

      RETURNING_VALUES :SUMB;

    TOT = TOT + SUMB;

  END

 

  SUSPEND;

END

 

Here's another. The DO section of the WHILE statement can be followed by a single statement, if you want to do more, you have to use a block.

 

EXECUTE UDSBLOCK (

  START_VALUE Integer)

AS

declare variable i integer;

declare variable pid integer;

declare variable n integer;

begin

  i = start_value;

  pid = null;

  n = 1;

  while (n < 1000)

  do begin

       insert into RECURSIVE_TEST(id, parent_id, USER_ID)

       values (:i, :pid, 'USER.' || :start_value);

       pid = i;

       i = i + 1;

       n = n + 1;

     end  

end