2015-05-11 72 views
2

我意外删除了我的触发器(需要重置我的数据库中的某些内容)。但我不知道如何使我的触发器再次..插入后循环触发器

我有一个2表。

1:

train_information:

train_information table

2:

桥:
axle table

Ñ ow,当列车被添加并插入到数据库表中时:train_information。我想要一个触发器来更新轴表。

触发后工作,我想车轴表的样子:

How i want the table to look after insert

不过。如果train_information有4个车轴。我只想把3放在轴台上。所以我想循环/触发器插入1少。 所以如果train_information表有20个轴。我想要轴表显示19等

+0

怎样的距离在'axle'计算? –

+0

距离稍后在窗体中更新。当我第一次插入它是NULL。 (这是一个屏幕截图,因此它包含一个值) – Mitch

回答

2

你可以有以下触发作为

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 ; 
+0

这样做:)非常感谢! – Mitch

1

下面的脚本将让你去。该脚本将循环插入的轴的数量。

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 ; 
+0

非常感谢:D – Mitch