在MySql数据集中使用for循环

时间:2013-05-28 04:36:24

标签: mysql sql database plsql

如何在MySQL数据集中使用for循环?

FOR x IN (SELECT column FROM table_name WHERE column_2 = input_val) 
LOOP
    sum_total := sum_total + x.column ;
END LOOP;

这是我用来循环oracle数据集的一个例子。

如何在MySql中实现这一目标?

2 个答案:

答案 0 :(得分:3)

根本不循环。 毕竟是SQL。

SELECT SUM(`column`) total
  FROM table_name 
  WHERE column_2 = <input_val>

否则使用CURSOR

现在,使用CURSOR的等效循环看起来像

DELIMITER $$
CREATE PROCEDURE sp_loop(IN input_val INT)
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE sum_current, sum_total INT DEFAULT 0;
  DECLARE cur1 CURSOR FOR SELECT column1 FROM table_name WHERE column2 = input_val;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;

  read_loop: LOOP
    FETCH cur1 INTO sum_current;
    IF done THEN
      LEAVE read_loop;
    END IF;
    SET sum_total = sum_total + sum_current;
  END LOOP;

  CLOSE cur1;
  SELECT sum_total;
END$$
DELIMITER ;

这是 SQLFiddle

答案 1 :(得分:0)

DROP PROCEDURE IF EXISTS  `foo`.`usp_cursor_example`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `foo`.`usp_cursor_example`(
  IN name_in VARCHAR(255)
)
READS SQL DATA
BEGIN

  DECLARE name_val VARCHAR(255);
  DECLARE status_update_val VARCHAR(255);

  -- Declare variables used just for cursor and loop control
  DECLARE no_more_rows BOOLEAN;
  DECLARE loop_cntr INT DEFAULT 0;
  DECLARE num_rows INT DEFAULT 0;

  -- Declare the cursor
  DECLARE friends_cur CURSOR FOR
    SELECT
        name
      , status_update
    FROM foo.friend_status
    WHERE name = name_in;

  -- Declare 'handlers' for exceptions
  DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET no_more_rows = TRUE;


  OPEN friends_cur;
  select FOUND_ROWS() into num_rows;

  the_loop: LOOP

    FETCH  friends_cur
    INTO   name_val
    ,      status_update_val;


    IF no_more_rows THEN
        CLOSE friends_cur;
        LEAVE the_loop;
    END IF;

    select name_val, status_update_val;

    -- count the number of times looped
    SET loop_cntr = loop_cntr + 1;

  END LOOP the_loop;

  -- 'print' the output so we can see they are the same
  select num_rows, loop_cntr;

END
DELIMITER ;