Do Case

This control structure lets you choose among multiple, mutually exclusive alternatives. You lay out the choices and exactly one is chosen. When you only have two choices, IF is more appropriate. To choose among alternatives in expressions, use IIF().

Usage

DO CASE
CASE lCondition1
     Commands
[ CASE lCondition2
     Commands
[ CASE lCondition3
     Commands
[ ... ] ] ]
[ OTHERWISE
     Commands ]
ENDCASE
The conditions are evaluated in sequence. As soon as VFP finds a case whose condition evaluates to true, the commands following that case are executed. Execution then continues following the ENDCASE. If there's an OTHERWISE clause and no case before it has a true condition, the commands following OTHERWISE are executed.Because the conditions are evaluated in order, you can assume previous conditions have failed in writing conditions for later cases. The following code displays a message about an employee based on his or her age.

Example

nThisYear = YEAR(DATE())
DO CASE
CASE nThisYear - YEAR(Birth_Date) >= 70
   ? 'Golden Oldie'
CASE nThisYear - YEAR(Birth_Date) >= 60
   ? 'SixtySomething'
CASE nThisYear - YEAR(Birth_Date) >= 50
   ? 'FiftySomething'
CASE nThisYear - YEAR(Birth_Date) >= 40
   ? 'FortySomething'
CASE nThisYear - YEAR(Birth_Date) >= 30
   ? 'ThirtySomething'
CASE nThisYear - YEAR(Birth_Date) >= 20
   ? 'Babe in the Woods'
OTHERWISE
   ? 'Wunderkind'
ENDCASE
Each case after the first in the example assumes the failure of the previous cases and doesn't bother to check whether the age is less than the upper limit for the group.We suggest you always include an OTHERWISE case. Without OTHERWISE, if none of the cases test true, execution continues on the line following the ENDCASE, with no error message. After you have coded all the possible cases and none could ever, ever be left, code an OTHERWISE as an error trap. You'll be surprised how often they come up!Remember that even though DO CASE looks like it can handle multiple records, it's just a branching command. It executes only once unless you put it inside a loop.

See Also

If, IIf()


Back to Table of Contents

Copyright © 2002-2018 by Tamar E. Granor, Ted Roche, Doug Hennig, and Della Martin. Click for license .