query_script_while
QueryScript Flow Control: while statement
SYNOPSIS
while (expression) statement; [otherwise statement;]
DESCRIPTION
while is a flow control looping structure. It makes for a condition test based on a given expression.
As long as the expression holds true, the statement (or block of statements) following the while statement are executed. The expression is evaluated before each iteration of the loop.
The while loop terminates in the following cases:
- The expression does not hold true
- A break statement is executed inside the loop (but not inside a nested loop)
- A return statement is executed inside the loop
- An uncaught error is raised (at the moment all errors are by default uncaught unless handled in user code)
The otherwise clause is optional. It will execute once should no iteration take place. That is, if at least one while iteration executes, otherwise is skipped.
Empty statements are not allowed in QueryScript. However, empty blocks are, and the while clause may be followed by an empty block, or by the do-nothing pass statement.
EXAMPLES
Remove leading digits from text:
set @txt := '12864xyz'; while(left(@txt,1) in ('0','1','2','3','4','5','6','7','8','9')) set @txt := substring(@txt, 2); SELECT @txt; +------+ | @txt | +------+ | xyz | +------+
DELETE statement as expression:
while (DELETE FROM world.Country WHERE Continent = 'Asia' LIMIT 10) { -- We remove 10 rows at a time, and throttle by waiting in between -- deletions twice the amount of time executed on deletion. throttle 2; }
Repeatedly issue a query for 60 seconds. Output number of repetitions:
set @counter := 0; while(script_runtime() < 60) { SELECT Continent, COUNT(*) FROM world.Country GROUP BY Continent; set @counter := @counter + 1; } SELECT @counter; +----------+ | @counter | +----------+ | 15654 | +----------+
Use an otherwise clause:
set @count := 0; while (@count > 22) set @count := @count-1; otherwise echo 'not a single iteration'; +--------------------------+ | echo | +--------------------------+ | 'not a single iteration' | +--------------------------+