触发语法和IF ELSE那么

时间:2011-03-11 10:53:53

标签: mysql sql triggers

我想创建一个触发器,用于计算具有特定id(id_ort)的行数。 如果它找到超过5行,我需要增加一个变量。

触发器语法

BEGIN
DECLARE nb INT;
DECLARE nba INT;

SET nba =0;


SET NEW.`VPLS_ID_NodeB` = CONCAT("21100", LPAD(NEW.`VPLS_ID_NodeB`,4,0));


SET nb = (SELECT COUNT(DISTINCT(`VPLS_ID_aggregation`)) FROM `VPLS_nodeB` WHERE `id_ORT` = NEW.`id_ORT`);

IF(nb > 5) THEN
SET nba = nb + 1;
ELSE
SET nba = nb;
END IF;


SET NEW.`VPLS_ID_aggregation` = CONCAT("21188", LPAD(NEW.`id_ORT`,2,0), LPAD(nba,2,0));
END

然而,有一个错误......即使我少于5行,每次都会增加var。

有什么想法吗?也许这是一个语法问题...

非常感谢!

1 个答案:

答案 0 :(得分:4)

你可能忘了指定一个分隔符我还做了一些其他更改,你可以看到

delimiter #

create trigger VPLS_nodeB_before_ins_trig before insert on VPLS_nodeB
for each row

BEGIN
DECLARE nb INT default 0;
DECLARE nba INT default 0;

SET NEW.VPLS_ID_NodeB = CONCAT('21100', LPAD(NEW.VPLS_ID_NodeB,4,0));
SET nb = (SELECT COUNT(DISTINCT(VPLS_ID_aggregation)) FROM VPLS_nodeB WHERE id_ORT = NEW.id_ORT);

IF(nb > 5) THEN
    SET nba = nb + 1;
ELSE
    SET nba = nb;
END IF;

SET NEW.VPLS_ID_aggregation = CONCAT('21188', LPAD(NEW.id_ORT,2,0), LPAD(nba,2,0));

END#

delimiter ;