IF statement in a LOOP statement : IF statement « Procedure Function « SQL / MySQL






IF statement in a LOOP statement

 
mysql>
mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE myProc()
    -> BEGIN
    ->
    ->     DECLARE i int;
    ->     SET i=0;
    ->     loop1: REPEAT
    ->          SET i=i+1;
    ->          IF MOD(i,2)<>0 THEN /*Even number - try again*/
    ->             SELECT CONCAT(i," is an odd number");
    ->          END IF;
    ->     UNTIL i >= 10
    ->     END REPEAT;
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter ;
mysql> call myProc();
+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 1 is an odd number            |
+-------------------------------+
1 row in set (0.00 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 3 is an odd number            |
+-------------------------------+
1 row in set (0.33 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 5 is an odd number            |
+-------------------------------+
1 row in set (0.33 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 7 is an odd number            |
+-------------------------------+
1 row in set (0.34 sec)

+-------------------------------+
| CONCAT(i," is an odd number") |
+-------------------------------+
| 9 is an odd number            |
+-------------------------------+
1 row in set (0.34 sec)

Query OK, 0 rows affected (0.34 sec)

mysql> drop procedure myProc;
Query OK, 0 rows affected (0.00 sec)

mysql>

        








Related examples in the same category

1.IF
2.If statement with ELSEIF and ELSE
3.Using OR in an IF statement
4.Check version with if statement