Multiple cursors in nested loops in MySQL

前端 未结 5 557
半阙折子戏
半阙折子戏 2021-02-05 11:14

I wish to do something which appear a bit complicated in MySQL. In fact, I wish to open a cursor, do a loop, and in this loop, open a second cursor using the data from the previ

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 11:38

    DECLARE _idp INT;
    DECLARE _cant INT;
    DECLARE _rec INT;
    DECLARE done INT DEFAULT 0;
    -- Definición de la consulta
    DECLARE primera CURSOR FOR SELECT dp.id_prod, SUM(dp.cantidad) AS cantidad, pp.receta FROM tm_detalle_pedido AS dp INNER JOIN tm_producto_pres AS pp
    DECLARE segunda CURSOR FOR SELECT id_ins, cant FROM tm_producto_ingr WHERE id_pres = _idp;
    
    -- Declaración de un manejador de error tipo NOT FOUND
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    
    -- Abrimos el primer cursor
    OPEN primera;
    
    REPEAT
    
    FETCH primera INTO _idp, _cant, _rec;
    
    IF NOT done THEN
    
     OPEN segunda;
     block2: BEGIN
         DECLARE doneLangLat INT DEFAULT 0;
         DECLARE _ii INT;
         DECLARE i FLOAT;
         DECLARE _canti FLOAT;
         DECLARE CONTINUE HANDLER FOR NOT FOUND SET doneLangLat = 1;
    
         REPEAT
         FETCH segunda INTO _ii,_canti;
         IF NOT doneLangLat THEN
            IF _rec = 1 THEN
                SET i = _canti * _cant;
                -- Insertamos
                INSERT INTO tm_inventario (id_ins,id_tipo_ope,id_cv,cant,fecha_r) 
                VALUES (_ii, 2, @id, i, _fecha);
            END IF;
         END IF;
         UNTIL doneLangLat END REPEAT;
    
      END block2;
      CLOSE segunda;
    
     END IF;
    
     UNTIL done END REPEAT;
     CLOSE primera;
    

提交回复
热议问题