while

Sets a condition for the repeated execution of a statement or statement block. The statements are executed repeatedly, as long as the specified condition is true.

Syntax

while logical_expression [plan "abstract plan"] statement

Parameters

Examples

Usage

  • The execution of statements in the while loop can be controlled from inside the loop with the break and continue commands.

  • The continue command causes the while loop to restart, skipping any statements after the continue. The break command causes an exit from the while loop. Any statements that appear after the keyword end, which marks the end of the loop, are executed. The break and continue commands are often activated by if tests.

    For example:
    while (select avg (price) from titles) < $30 
    begin 
            update titles 
            set price = price * 2 
        if (select max (price) from titles) > $50 
            break 
        else 
            if (select avg (price) from titles) > $30
               continue 
            print "Average price still under $30"
    end 
    
    select title_id, price from titles
            where price > $30

    This batch continues to double the prices of all books in the titles table as long as the average book price is less than $30. However, if any book price exceeds $50, the break command stops the while loop. The continue command prevents the print statement from executing if the average exceeds $30. Regardless of how the while loop terminates (either normally or because of the break command), the last query indicates which books are priced over $30.

  • If two or more while loops are nested, the break command exits to the next outermost loop. All the statements after the end of the inner loop run, then the next outermost loop restarts.

    Warning!  If a or create view command occurs within a while loop, the SAP ASE server creates the schema for the table or view before determining whether the condition is true. This may lead to errors if the table or view already exists.

Standards

ANSI SQL – Compliance level: Transact-SQL extension.

Permissions

No permission is required to use while.

Related reference
begin...end
break
continue
goto label