The
WHILE
Flow element
T-SQL provides the WHILE element to enable you to execute code in a loop. The WHILE element
executes a statement or statement block repeatedly while the predicate you specify after the WHILE
keyword is TRUE. When the predicate is FALSE or UNKNOWN, the loop terminates.
T-SQL doesn’t provide a built-in looping element that executes a predetermined number of times,
but it’s very easy to mimic such an element with a WHILE loop and a variable. For example, the fol-
lowing code demonstrates how to write a loop that iterates 10 times.
DECLARE @i AS INT = 1;
WHILE @i <= 10
BEGIN
PRINT @i;
SET @i = @i + 1;
END;
The code declares an integer variable called @i that serves as the loop counter and initializes it
with the value 1. The code then enters a loop that iterates while the variable is smaller than or equal
to 10. In each iteration, the code in the loop’s body prints the current value of @i and then increments
it by 1. This code returns the following output showing that the loop iterated 10 times.
www.it-ebooks.info
Do'stlaringiz bilan baham: |