7.6.4. BEGIN …​ END

Used for

Delineating a block of statements

Available in

PSQL

Syntax

  1. <block> ::=
  2. BEGIN
  3. [<compound_statement>
  4. …]
  5. END
  6. <compound_statement> ::= {<block> | <statement>;}

The BEGIN …​ END construct is a two-part statement that wraps a block of statements that are executed as one unit of code. Each block starts with the half-statement BEGIN and ends with the other half-statement END. Blocks can be nested to unlimited depth. They may be empty, allowing them to act as stubs, without the need to write dummy statements.

The BEGIN and END statements have no line terminators. However, when defining or altering a PSQL module in the isql utility, that application requires that the last END statement be followed by its own terminator character, that was previously switched, using SET TERM, to some string other than a semicolon. That terminator is not part of the PSQL syntax.

The final, or outermost, END statement in a trigger terminates the trigger. What the final END statement does in a stored procedure depends on the type of procedure:

  • In a selectable procedure, the final END statement returns control to the caller, returning SQLCODE 100, indicating that there are no more rows to retrieve

  • In an executable procedure, the final END statement returns control to the caller, along with the current values of any output parameters defined.

Example

A sample procedure from the employee.fdb database, showing simple usage of BEGIN…​END blocks:

  1. SET TERM ^;
  2. CREATE OR ALTER PROCEDURE DEPT_BUDGET (
  3. DNO CHAR(3))
  4. RETURNS (
  5. TOT DECIMAL(12,2))
  6. AS
  7. DECLARE VARIABLE SUMB DECIMAL(12,2);
  8. DECLARE VARIABLE RDNO CHAR(3);
  9. DECLARE VARIABLE CNT INTEGER;
  10. BEGIN
  11. TOT = 0;
  12. SELECT
  13. BUDGET
  14. FROM
  15. DEPARTMENT
  16. WHERE DEPT_NO = :DNO
  17. INTO :TOT;
  18. SELECT
  19. COUNT(BUDGET)
  20. FROM
  21. DEPARTMENT
  22. WHERE HEAD_DEPT = :DNO
  23. INTO :CNT;
  24. IF (CNT = 0) THEN
  25. SUSPEND;
  26. FOR
  27. SELECT
  28. DEPT_NO
  29. FROM
  30. DEPARTMENT
  31. WHERE HEAD_DEPT = :DNO
  32. INTO :RDNO
  33. DO
  34. BEGIN
  35. EXECUTE PROCEDURE DEPT_BUDGET(:RDNO)
  36. RETURNING_VALUES :SUMB;
  37. TOT = TOT + SUMB;
  38. END
  39. SUSPEND;
  40. END^
  41. SET TERM ;^

See also

EXIT, LEAVE, SET TERM