2.7 Block StructurePL/SQL is a block-structured language. Each of the basic programming units you write to build your application is (or should be) a logical unit of work. The PL/SQL block allows you to reflect that logical structure in the physical design of your programs. The block structure is at the core of two key concepts and features of the PL/SQL language:
You can create anonymous blocks (blocks of code that have no name) and named blocks, which are procedures and functions. Furthermore, you can build packages in PL/SQL that group together multiple procedures and functions. The following sections briefly examine the block structure and related concepts. 2.7.1 Sections of the PL/SQL BlockEach PL/SQL block has up to four different sections (some are optional under certain circumstances):
Figure 2.1 shows the structure of the PL/SQL block for a procedure. Figure 2.1: The PL/SQL block structureThe ordering of the sections in a block corresponds to the way you would write your programs and the way they are executed:
2.7.2 Scope of a BlockIn the declaration section of the block, you may define variables, modules, and other structures. These declarations are local to that block. When the execution of the block finishes, those structures no longer exist. For example, if you open a cursor in a block, that cursor is automatically closed at the end of the block. The block is the scope of any objects declared in that block. The block also provides the scope for exceptions that are declared and raised. In fact, one of the most important reasons to create a block is to take advantage of the exception section that comes with that block. It gives you a finer granularity of control over how you can handle errors in your programs. 2.7.3 Nested BlocksA block may also contain nested sub-blocks of code. The following example shows a procedure with an anonymous, nested block defined within it: PROCEDURE calc_totals IS year_total NUMBER; BEGIN year_total := 0; /* Nested anonymous block */ DECLARE month_total NUMBER; BEGIN month_total := year_total / 12; END; END; Notice that I can reference the year_total variable inside the nested block. Any element declared in an outer block is global to all blocks nested within it. Any element declared within an inner block cannot, however, be referenced in an outer block. Although I refer to the PL/SQL block structure throughout this book, it will figure most prominently in Part 4, Modular Code . Copyright (c) 2000 O'Reilly & Associates. All rights reserved. |
|