sajad torkamani

Here’s a stored procedure that loops through the numbers 1 to 5 and returns their sum:

CREATE PROCEDURE sum_nums_1_to_5()
BEGIN
    DECLARE sum INT DEFAULT 0;
    DECLARE counter INT DEFAULT 0;

    my_loop:
    LOOP
        # Initialize counter
        SET counter = counter + 1;

        # If counter is greater than 5, leave the loop
        IF counter > 5 THEN
            LEAVE my_loop;
        END IF;

        SET sum = sum + counter;
    END LOOP my_loop;

    SELECT sum;
END;

Call loop:

CALL sum_nums_1_to_5
Tagged: MySQL