Home > Articles > Data > DB2

DB2 SQL Procedural Language: Using Flow of Control Statements

Learn how to use flow of control statements to write powerful SQL stored procedures and discover all the necessary commands to accomplish this task. You will also learn how flow of control statements can help control the sequence of statement execution.
This chapter is from the book

In this chapter, you will learn:

how to use the compound statement;

how to use labels in both compound statements and loops;

how to use the two conditional statements (IF and CASE);

how to use the four looping statements (FOR, WHILE, REPEAT, and LOOP);

how to use the four transfer of control statements (GOTO, LEAVE, ITERATE and RETURN).

Sequential execution is the most basic path that program execution can take. With this method, the program starts execution at the first line of the code, followed by the next, and continues until the final statement in the code has been executed. This approach works fine for very simple tasks but tends to lack usefulness since it can only handle one situation. Like humans, most programs need to be able to decide what to do in response to changing circumstances. By controlling a code's execution path, a specific piece of code can then be used to handle intelligently more than one situation.

Flow of control statements are used to control the sequence of statement execution. Statements such as IF and CASE are used to conditionally execute blocks of SQL Procedural Language (SQL PL) statements, while other statements, such as WHILE and REPEAT, are typically used to execute a set of statements repetitively until a task is complete.

Although there are many flow of control statements to be discussed in this chapter, there are three main categories: conditional statements, loop statements, and transfer of control statements. Before jumping into a discussion on flow of control statements, it is important to first understand the use of compound statements.

3.1 Compound Statements

Of all the SQL control statements, the compound statement is the easiest to work with and understand. Compound statements are used to group together a set of related lines of code. You can declare variables, cursors, and condition handlers and use flow of control statements within a compound statement (cursors and condition handlers are discussed in later chapters).

BEGIN and END are keywords that define a compound statement. The BEGIN keyword defines the starting line of code for the compound statement, while the END keyword defines the final line of code. Compound statements are used to control variable scoping and for executing more than a single statement where a single statement is expected (such as within a condition handler, which will be discussed in Chapter 5, "Condition Handling").

Each compound statement has its own scope, where only variables and the like that have been declared within the same compound statement or within enclosing compound statements can be seen. That is, statements within one compound statement may not be able to refer to variables and values that are declared within another compound statement, even if both compound statements are part of the same SQL procedure body.

It is perfectly logical and, in most cases, completely valid to have the ability to define as many compound statements as needed within an SQL procedure (see ATOMIC for the exception). These compound statements are typically used to introduce scoping and a logical separation of related statements.

There is a specific order for declaring variables, conditions, cursors and handlers within a compound statement. Specifically, the order of declarations must proceed as follows:

BEGIN variable declarations condition declarations cursor declarations handler declarations assignment, flow of control, SQL statements, and other compound statements END

Don't worry if you are not familiar with some of the above terms, as they will be discussed in greater detail later. Also, notice that one or several compound statements can be nested within other compound statements. In such cases, the same order of declarations continues to apply at each level.

It is important to understand the type of variable scoping (or visibility) that occurs when a compound statement has been defined. Specifically:

Outer compound statements cannot see variables declared within inner compound statements.

Inner compound statements can see variables that have been declared in outer compound statements.

Scoping is illustrated in Figure 3.1.

Figure 3.1 Variable Scoping Example

BEGIN                               -- (1) 
    DECLARE v_outer1 INT; 
    DECLARE v_outer2 INT; 


    BEGIN	                    -- (2)	 
        DECLARE v_inner1 INT;	 
        DECLARE v_inner2 INT;	  	 	 
 	 	 
        SET v_outer1 = 100;	    -- (3)	 
        SET v_inner1 = 200;	    -- (4)	 
    END;	-- (5)	  	 	 
 	 	 
    SET v_outer2 = 300;	            -- (6)	 
    SET v_inner2 = 400;	            -- (7)	 
END -- (8)

In the above, (1) and (8) define the outer compound statement, while (2) and (5) define the inner compound statement. All statements, except statement (7), will succeed. Statement (7) fails because an outer compound statement cannot see a variable declared within an inner compound statement. You will receive an SQLSTATE 42703 error with the message "'V_INNER2' is not valid in the context where it is used."

Scoping can be especially useful in the case of looping and exception handling, allowing the program flow to jump from one compound statement to another.

There are two distinct types of compound statements, which both serve a different purpose.

3.1.1 NOT ATOMIC Compound Statement

The previous example illustrated a NOT ATOMIC compound statement and is the default type used in SQL procedures. If an unhandled error (that is, no condition handler has been declared for the SQLSTATE raised) occurs within the compound statement, any work which is completed before the error will not be rolled back, but will not be committed either. The group of statements can only be rolled back if the unit of work is explicitly rolled back using ROLLBACK or ROLLBACK TO SAVEPOINT (the latter is discussed in Chapter 8, "Advanced Features"). You can also COMMIT successful statements if it makes sense to do so.

The syntax to for a NOT ATOMIC compound statement is shown in Figure 3.2.

Figure 3.2 NOT ATOMIC Compound Statement Syntax Diagram

.-NOT ATOMIC--. 
>>-+---------+--BEGIN----+-------------+------------------------> 
   '-label:--' 

... 
Misc. Statements; 
... 
>-------------------------------------+---END--+--------+------>< 
                                               '-label--' 

The optional label is used to define a name for the code block. The label can be used to qualify SQL variables declared within the compound statement. If the ending label is used, it must be the same as the beginning label. We will learn more about labels later in this chapter.

The use of the NOT ATOMIC keywords is optional, but usually suggested, as it reduces ambiguity of the code.

The SQL procedure illustrated in Figure 3.3 demonstrates the non-atomicity of NOT ATOMIC compound statements:

Figure 3.3 NOT ATOMIC Compound Statement Example

CREATE PROCEDURE not_atomic_proc () 
    SPECIFIC not_atomic_proc 
    LANGUAGE SQL 
BEGIN NOT ATOMIC 
    -- Declare variables 
    DECLARE v_job VARCHAR(8); 
    -- Procedure logic 
    INSERT INTO atomic_test(proc, res) 
           VALUES ('Not_Atomic_Proc','Before error test'); 
    SIGNAL SQLSTATE '70000';                                         -- (1) 
    INSERT INTO atomic_test(proc, res) 
         VALUES ('Not_Atomic_Proc','After error test'); 
END 

Right now, it is sufficient to understand that the SIGNAL statement at (1) is used to explicitly raise an error. Additionally, since this error is unhandled, the procedure will exit right after the error.

After calling this procedure, you will see that although an error has been raised halfway through execution, the first INSERT successfully inserted a row into the atomic_test table. It has not been committed or rolled back, however.

3.1.2 ATOMIC Compound Statement

The ATOMIC compound statement, as the name suggests, can be thought of as a singular whole—if any unhandled error conditions arise within it, all statements which have been executed up to that point are considered to have failed as well and are therefore rolled back. ATOMIC compound statements cannot be nested inside other ATOMIC compound statements.

In addition, you cannot use SAVEPOINTs or issue explicit COMMITs or ROLLBACKs from within an ATOMIC compound statement.

NOTE

COMMIT, ROLLBACK, SAVEPOINTS and nested ATOMIC compound statements are not allowed within an ATOMIC compound statement.

The syntax to declare an ATOMIC compound statement is shown in Figure 3.4.

Figure 3.4 ATOMIC Compound Statement Syntax Diagram

>>-+---------+--BEGIN ATOMIC------------------------------------> 
   '-label:--' 

... 
Misc. Statements; 
... 
>-------------------------------------+---END--+--------+------>< 
                                               '-label--' 

A label is used in the same way as with a NOT ATOMIC compound statement.

The example in Figure 3.5 illustrates the behavior of an ATOMIC compound statement. It is quite similar to the NOT ATOMIC example above, and only differs in name and the fact that it uses an ATOMIC compound statement.

Figure 3.5 ATOMIC Compound Statement Example

CREATE PROCEDURE atomic_proc () 
    SPECIFIC atomic_proc 
    LANGUAGE SQL 
BEGIN ATOMIC 
   -- Declare variables 
   DECLARE v_job VARCHAR(8); 
   -- Procedure logic 
   INSERT INTO atomic_test(proc, res) 
        VALUES ('Atomic_Proc','Before error test'); 
   SIGNAL SQLSTATE '70000';                                   -- (1)
   INSERT INTO atomic_test(proc, res) 
        VALUES ('Atomic_Proc','After error test');  
END 

When the error condition of SQLSTATE 70000 is raised at (1), the unhandled error causes procedure execution to stop. Unlike the NOT ATOMIC example in Figure 3.3, the first INSERT statement will be rolled back, resulting in a table with no inserted rows from this procedure.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020