如何在一个触发器内放置多组方程

时间:2013-09-15 10:50:36

标签: mysql database

    CREATE TABLE IF NOT EXISTS `test` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `ia_att` decimal(3,2) NULL,
      `t1` decimal(3,2) NULL,
      `t2` decimal(3,2) NULL,
      `t3` decimal(3,2) NULL,
      `ia_tot` decimal(3,2) NULL,
      .....
      .....
      PRIMARY KEY (`id`),
    );      

 CREATE TRIGGER tg_bi_test
    BEFORE INSERT ON test
    FOR EACH ROW 
      SET NEW.s1_ia_tot = 
         (NEW.s1_t1 + NEW.s1_t2 + NEW.s1_t3 -
          LEAST(NEW.s1_t1, NEW.s1_t2, NEW.s1_t3)) / 2 + 
         CASE 
           WHEN NEW.s1_ia_att > 95 THEN 5
           WHEN NEW.s1_ia_att BETWEEN 81 AND 95 THEN 4
           WHEN NEW.s1_ia_att BETWEEN 76 AND 80 THEN 3
           WHEN NEW.s1_ia_att BETWEEN 61 AND 75 THEN 2
           WHEN NEW.s1_ia_att < 60 THEN 0 

      SET NEW.s2_ia_tot = 
         (NEW.s2_t1 + NEW.s2_t2 + NEW.s2_t3 -
          LEAST(NEW.s2_t1, NEW.s2_t2, NEW.s2_t3)) / 2 + 
         CASE 
           WHEN NEW.s2_ia_att > 95 THEN 5
           WHEN NEW.s2_ia_att BETWEEN 81 AND 95 THEN 4
           WHEN NEW.s2_ia_att BETWEEN 76 AND 80 THEN 3
           WHEN NEW.s2_ia_att BETWEEN 61 AND 75 THEN 2
           WHEN NEW.s2_ia_att < 60 THEN 0
           --------
           --------
         END;

创建这样的触发器有什么问题?我想在一个表中为七个coloums创建这个ia_tot请帮助我这可能在mysql中

1 个答案:

答案 0 :(得分:0)

一点提示 - 创建一个用户定义的函数来完成所有计算:

delimiter $$
create function my_calculation( ia_att decimal, t1 decimal, t2 decimal, t3 decimal )
returns int
deterministic 
begin 
  RETURN
  (t1 + t2 + t3 - LEAST(t1, t2, t3)) / 2
  +
  CASE 
    WHEN ia_att > 95 THEN 5
    WHEN ia_att BETWEEN 81 AND 95 THEN 4
    WHEN ia_att BETWEEN 76 AND 80 THEN 3
    WHEN ia_att BETWEEN 61 AND 75 THEN 2
    WHEN ia_att < 60 THEN 0 
   END;
END $$
DELIMITER ;

并在触发器中使用此功能:

delimiter $$
create trigger abc before insert 
on `test` for each row
begin
   declare `value` decimal;

   SET NEW.s1_ia_tot = my_calculation( NEW.s1_ia_att, NEW.s1_t1, NEW.s1_t2, NEW.s1_t3 );
   SET NEW.s2_ia_tot = my_calculation( NEW.s2_ia_att, NEW.s2_t1, NEW.s2_t2, NEW.s2_t3 );
   SET NEW.s3_ia_tot = my_calculation( NEW.s3_ia_att, NEW.s3_t1, NEW.s3_t2, NEW.s3_t3 );
   ......
end $$
delimiter ; 

这将使您的代码更短,更清晰,更易于维护
另一个注释 - DECIMAL(3,2)存储最多3位数字,小数点右边2位数字。那个测量点,在decimall点的左边只有一个数字(3 - 2 = 1),并且可以存储最多9.99的数字,而不是更多。如果数字是10或更多,您将收到错误。

----编辑-----
这是一个工作演示的链接 - &gt; http://sqlfiddle.com/#!2/93c8d/4