IF statement

From sasCommunity
Jump to: navigation, search

The IF statement allows the conditional execution of DATA Step statements. IF statements are used to make decisions about what portions of code are executed in differing circumstances.

Syntax

The IF statement has several variants.

Subsetting IF statement

IF logical expression ;

The subsetting IF statement conditionally executes the remaining statements in the data step only if the logical expression is true. If the logical expression is false then no further processing takes place on the existing record from the input data set, it does not get outputted and the DATA Step starts its next iteration. It is equivalent to conditionally executing a DELETE statement using the code:

IF NOT( logical expression ) THEN DELETE ;

IF THEN statement

IF logical expression THEN statement or DO group ;

The IF THEN statement conditionally executes the statement following the THEN keyword only if the logical expression is true. If the logical expression is false then the statement is not executed. If more than one statement needs to be executed then a simple DO group needs to be used, like so.

IF logical expression THEN DO zero or more statements ; END ;

IF THEN ELSE statement

IF logical expression THEN statement or DO group ;
ELSE statement or DO group ;

The IF THEN ELSE statement conditionally executes the statement following the THEN keyword only if the logical expression is true. But if the logical expression is false then the statement following the ELSE keyword is executed instead. The ELSE statement must be the next statement immediately follow the statement or DO group after the THEN keyword.

Usage

IF statements can be nested or chained.

ELSE IF chains

One usage is ELSE keyword followed by an IF statement. Sometimes this construction is known as an ELSE IF statement or chain. For efficiency such chains of statements should be constructed with the most likely condition at the top of the chain and the least likely at the bottom. Alternatively, a SELECT statement can be used.

See also