IF /THEN / ELSE

IF / THEN / ELSE

Top  Previous  Next

 

The IF statement provides conditional execution of one or more statements.

 

 

Format

 

IF expr

{THEN statement(s)}

{ELSE statement(s)}

 

where

 

expris an expression which can be resolved to a numeric value

 

statement(s)are statements to be executed depending on the value of expr.

 

At least one of the THEN and ELSE clauses must be present. If both are used, the THEN clause must be first. An IF statement with just an ELSE clause is syntactically valid but likely to be difficult to understand.

 

The newline before the THEN and ELSE clauses is optional.

 

The statement(s) under the THEN clause are executed if the value of expr is non-zero. The statement(s) under the ELSE clause are executed if the value of expr is zero.

 

Where the keyword THEN or ELSE is followed by an executable statement on the same line, the condition applies to that statement. If there is nothing else or only a comment on the line, the conditioned statement(s) must appear on subsequent lines terminated by an END statement. For example:

 

IF QTY > 99 THEN

  LARGE.ORDER = @TRUE

  DISCOUNT = 0.1

END

 

Alternatively, this could be written using semicolons to separate the conditioned statements:

 

IF QTY > 99 THEN LARGE.ORDER = @TRUE ; DISCOUNT = 0.1

 

Use of this format is discouraged as the semantics differ across multivalue database products.

 

 

IF QTY > QOH THEN

  DISPLAY 'Insufficient stock'

END ELSE

  QOH -= QTY

  DISPLAY 'Order confirmed'

END

 

The above program fragment might be used to compare the quantity in an order (QTY) with the quantity on hand (QOH), taking different paths dependant on whether there is sufficient stock. Note the need for the END to terminate the THEN clause as, unlike some other programming languages, the END pairs up with the THEN or ELSE and not with the IF.