M
M
malan2013-07-09 12:39:56
MySQL
malan, 2013-07-09 12:39:56

Similar to FOR… IN… LOOP in MySQL?

Oracle has a wonderful FOR… IN… LOOP construction that allows you to process the entire selection in a loop on request.
For example:

FOR rec IN (SELECT t.id, t.doc_type, t.guid, t.CAPTION FROM test_table  t)
LOOP
IF rec.id > 10 THEN Dbms_Output.put_line(rec.id||' '||rec.CAPTION); END IF;
END LOOP;

I can not find if there is an analogue of such a structure in MySQL?
UPD.
BEGIN
  DECLARE cur CURSOR FOR SELECT id, doc_type, guid, CAPTION FROM test_table  t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
Open cur;
WHILE not done  DO 
// cur - текущая запись
END WHILE;
Close cur; 
END;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
ohifck, 2013-07-09
@malan

See cursors.
for example

CREATE PROCEDURE curdemo()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE a CHAR(16);
  DECLARE b, c INT;
  DECLARE cur1 CURSOR FOR SELECT id,data FROM test.t1;
  DECLARE cur2 CURSOR FOR SELECT i FROM test.t2;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur1;
  OPEN cur2;

  read_loop: LOOP
    FETCH cur1 INTO a, b;
    FETCH cur2 INTO c;
    IF done THEN
      LEAVE read_loop;
    END IF;
    IF b < c THEN
      INSERT INTO test.t3 VALUES (a,b);
    ELSE
      INSERT INTO test.t3 VALUES (a,c);
    END IF;
  END LOOP;

  CLOSE cur1;
  CLOSE cur2;
END;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question