【问题标题】:Loop in trigger after insert插入后循环触发
【发布时间】:2018-03-14 19:18:00
【问题描述】:

我不小心删除了触发器(需要重置数据库中的某些内容)。但我不知道如何再次触发我的触发器..

我有两张桌子。

1:

train_information:

2:

车轴:

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

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

但是。如果 train_information 有 4 个轴。我只想把 3 放在轴表中。所以我希望循环/触发器少插入 1 个。 所以如果 train_information 表有 20 个轴。我希望轴表显示 19 等。

【问题讨论】:

  • axle 中的距离是如何计算的?
  • 距离稍后在表单中更新。当我第一次插入它时,它是 NULL。 (这是它工作时的屏幕截图,因此它包含一个值)

标签: mysql triggers


【解决方案1】:

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

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 ;

【讨论】:

  • 成功了 :) 非常感谢!
【解决方案2】:

以下脚本将助您一臂之力。该脚本将遍历插入的轴数。

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 ;

【讨论】:

  • 也非常感谢:D
猜你喜欢
  • 2011-11-07
  • 1970-01-01
  • 2015-08-17
  • 2012-03-30
  • 2013-12-06
  • 2016-10-13
  • 2016-01-27
相关资源
最近更新 更多