MySQL WHILE Loop Sum Even Numbers

One way to calculate the sum of even numbers using a WHILE loop in MySQL is as follows:

SET @sum = 0;
SET @i = 1;
WHILE @i <= 10 DO
    IF @i % 2 = 0 THEN
        SET @sum = @sum + @i;
    END IF;
    SET @i = @i + 1;
END WHILE;

SELECT @sum as sum_of_even_numbers;

In this example, we initialize the variable @sum to 0 and use the variable @i to iterate through the numbers 1 to 10. Within the loop, we check if the current @i is even, and if so, we add it to @sum. Finally, we output @sum as the sum of even numbers.

bannerAds