循环mysql查询内部触发器

时间:2017-02-14 23:40:29

标签: mysql sql triggers

这是我的触发器:

DELIMITER |

CREATE TRIGGER update_status_penjualan AFTER UPDATE
    ON penjualan FOR EACH ROW
BEGIN

DECLARE arrayresult = (SELECT * FROM rincian_penjualan WHERE id_penjualan = OLD.id)     

  for ids in arrayresults

      UPDATE buku SET stok = stok + ids['jumlah']; WHERE noisbn = ids['noisbn'];                    

  endfor

END;

|

DELIMITER ;

我发现了很多错误,我认为因为我的循环代码不正确。 谁能告诉我如何解决它? 谢谢〜

1 个答案:

答案 0 :(得分:0)

您可以尝试使用cursor,例如:

DELIMITER |

CREATE TRIGGER update_status_penjualan AFTER UPDATE
    ON penjualan FOR EACH ROW
BEGIN

declare jumlah_c int;
declare noisbn_c int;
declare done int;
declare cur1 cursor for 
SELECT * FROM rincian_penjualan WHERE id_penjualan = OLD.id;
declare continue handler for not found set done=1;

    set done = 0;
    open cur1;
    igmLoop: loop   
    fetch cur1 into jumlah_c,noisbn_c;
     if done = 1 then leave igmLoop; end if;

      UPDATE buku SET stok = stok + jumlah_c WHERE noisbn = noisbn_c;                    

    end loop igmLoop;
    close cur1;

END;

|

DELIMITER ;