The do..loop control statement is used in the script to iterate through one or more statements until a condition is met. It is useful when you need to dynamically check a condition while executing statements in the script. There are two ways the do..loop can be used. The first is to check the condition before executing statement(s) in the loop and the second is to check the condition after the statement(s) in the loop have been executed. Let’s look at some examples.
The script below checks to see if the condition has been met before the statements are executed. When x is no longer less than 10, the do..loop will stop.
The script below is a little different. In this script, the condition is checked after the statements are executed so the statements will always run at least one time.
Both scripts produce the same results as seen below. Products 1 through 9 were created.
The do..loop also can be used with the “Until” keyword instead of the “While” keyword producing different results. In the script below, the statements will be executed until x is less than 10. Since x is equal to 1 which is less than 10, the statements never run so no products are generated.
Now if the condition is checked after the statements are run, as shown in the script below, one product will be created since the statements run once before the condition is checked.
Now what if you need to exit the do..loop. You can do this using Exit do. The loop will be exited and execution will continue with the statement(s) following the loop. Here is an example of what this looks like. In the script below, the loop will exit after the Load statement runs 3 times, stopping when x is equal to 3.
In the script below, this loop will exit after the Load statement executes one time. Since x is not equal to 3, the loop will be exited when execution gets to the exit do statement.
The do..loop is helpful in the script when you need to execute statements while /until a condition is met. It provides flexibility since the condition can be dynamic and be evaluated before or after the statement(s) in the loop. This is a little different from the For..Next loop where a counter is used to determine the number of times the statement(s) in the loop are executed. Learn more about loops in Henric’s blog Loops in the Script.