使用mysqll程序计算20-50之间的偶数和奇数

时间:2016-11-26 09:29:16

标签: mysql for-loop stored-procedures

我很难完成我的作业,因为我是初学者使用mysql程序。 用循环搜索奇数和偶数在20-50之间的总数。 我想使用mysql程序调用这样的输出: total_odd_numbers:15 total_even_numbers:16

我试着总结一下这样的偶数:

`DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `genap`()
BEGIN
DECLARE x  INT;
DECLARE str  VARCHAR(255);
declare total int;

SET x = 20;
SET str =  '';
set total = 0;

 loop_label:  LOOP
 IF  x = 50  THEN 
 LEAVE  loop_label;
 END  IF;
             SET  x =x+1;

 IF  (x mod 2) THEN
 ITERATE  loop_label;


 ELSE
                SET  str = CONCAT(str,x,',');
                SET total= total+x;
 END  IF;
         END LOOP;    
         SELECT sum(total);

 END`

1 个答案:

答案 0 :(得分:0)

尝试此程序:

DROP PROCEDURE IF EXISTS ShowOddEvesBetween;
DELIMITER ;;
CREATE PROCEDURE ShowOddEvesBetween(IN fromNum INT, IN toNum INT)
 BEGIN
 DECLARE odds INT DEFAULT 0;
 DECLARE evens INT DEFAULT 0;
 DECLARE x INT;

 SET x = fromNum;

 WHILE x <= toNum DO
  IF x % 2 THEN
   SET odds = odds + 1;
  ELSE
   SET evens = evens + 1;
  END IF;

  SET x = x + 1;
 END WHILE;

 SELECT CONCAT("total_odd_numbers: ", odds, ", total_even_numbers: ", evens) AS "Odds & Evens";

 END;
;;

然后叫它

CALL ShowOddEvesBetween(20, 50);

将输出您想要的内容

MariaDB [test]> CALL ShowOddEvesBetween(20, 50);
+-----------------------------------------------+
| Odds & Evens                                  |
+-----------------------------------------------+
| total_odd_numbers: 15, total_even_numbers: 16 |
+-----------------------------------------------+
1 row in set (0.00 sec)