REPEAT is another useful looping construct. It’s somewhat easier to use in some circumstances than LOOP , because it has a terminating condition built into its syntax, as shown here: [label:] REPEAT The block of statements appearing between the REPEAT and UNTIL keywords is executed repeatedly until the condition indicated by UNTIL is met. Here’s an example of a stored procedure (named repeat_sum) that gets the sum of an integer and all positive integers less than itself using a REPEAT ... UNTIL loop:
In this procedure, we start by declaring a counter equal to 0, then, each time we go through the REPEAT loop, we increment it, adding it to the output parameter output, and then checking to see if it’s yet equal to the original value. When counter and value are equal, we exit the loop. We can test it as shown here:
The WHILE loop in some ways can be regarded as the inverse of a REPEAT loop. With a REPEAT loop, statements are executed until some condition is met. In a WHILE loop, execution of the statement block following the DO keyword continues only so long as the specified condition is true. Here’s the formal syntax for WHILE: [label:] WHILE condition DO In the next example, we use a WHILE loop in a stored function to obtain the factorial of an integer: The factorial of an integer is defined as the product of that integer and all the positive integers less than itself and greater than 1, so the factorial of 5 (often written as 5!) is 5 X 4 X 3 X 2 = 120, as you can see from our test of the factorial function above. 0! (zero factorial) is defined as 1 and the factorial of a negative number is undefined. With these additional conditions in mind, you could write a somewhat improved version of the stored function. This better_factorial function uses a CASE block to distinguish the cases where the input value is equal to or less than zero, and to act accordingly as shown here: CREATE FUNCTION better_factorial(value INT ) RETURNS INT This example also illustrates how you can nest multiple flow-control con structs inside one another within a single stored function or stored procedure.
blog comments powered by Disqus |