插入后在触发器中循环

Loop in trigger after insert

我不小心删除了触发器(需要重置数据库中的某些内容)。但是我不知道怎么重新触发..

我有 2 tables。

1:

train_information:

2:

车轴:

现在,当火车被添加并插入数据库时​​ table:train_information。我想要一个触发器来更新轴 table.

触发器工作后,我希望轴 table 看起来像:

不过。如果 train_information 有 4 个车轴。我只想在车轴上放 3 个 table。所以我希望 loop/trigger 少插入 1 个。 所以如果 train_information table 有 20 个车轴。我希望车轴 table 显示 19 等等

下面的脚本会让你开始。该脚本将遍历插入的轴数。

DELIMITER //

CREATE TRIGGER `train_information_after_insert` AFTER INSERT ON `train_information` 
FOR EACH ROW
BEGIN

DECLARE noAxles INT;
SET noAxles = NEW.number_of_axles;

myLoop: LOOP
  SET noAxles = noAxles - 1;

  //UPDATE STATEMENT FOR AXLE TABLE HERE

  IF noAxles = 0 THEN
    LEAVE myLoop;
  END IF;
END LOOP myLoop;

END//

DELIMITER ;

您可以将以下触发器设置为

delimiter //
create trigger train_information_ins after insert on train_information
for each row 
begin
 declare x int ;
 if(new.number_of_axies >  0 ) then
   set x = 1 ;
   while x < new.number_of_axies do
     insert into axle (train_id,axle)
     values
     (new.train_id,x);
     set x=x+1;
    end while ;
  end if ;
end;//

delimiter ;