MySQL trigger after insert and after update

后端 未结 2 1612
忘掉有多难
忘掉有多难 2021-01-15 04:22

I have two tables with one named att as follows

CREATE TABLE att (
  SID varchar(50) NOT NULL, 
  CID varchar(50) NOT NULL, 
  Date date NOT         


        
相关标签:
2条回答
  • 2021-01-15 05:19

    Make sure you change the delimiter before defining the trigger. Also make sure you're using the same table and column names when you create the table and the trigger (you're using att and attendance, and SID and StudID, in your examples).

    As it is, the trigger definition caused no error when I tested it in MySQL 5.1.55 after setting the delimiter.

    delimiter $$
    CREATE TRIGGER `att_up` 
      AFTER UPDATE ON `attendance`
    FOR EACH ROW 
    BEGIN
      DECLARE Zeros INT;
      DECLARE Ones INT;
      DECLARE total INT;
      DECLARE attend FLOAT;
      SELECT SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)), 
             SUM(h1+h2+h3+h4+h5+h6+h7+h8),
             SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8)) + SUM(h1+h2+h3+h4+h5+h6+h7+h8)
        INTO Zeros, Ones, Total FROM attendance 
        WHERE SID=NEW.SID;
      SET attend=((Zeros-Ones)/total)/100;
      INSERT INTO per (SID, CID, per) values (NEW.SID, NEW.CID, attend)
        ON DUPLICATE KEY UPDATE per=attend;
    END$$
    delimiter ;
    
    0 讨论(0)
  • 2021-01-15 05:23
    DELIMITER $$
    
    CREATE TRIGGER `att_up` AFTER UPDATE ON `attentance`
    FOR EACH ROW
    
    BEGIN
    
    SET @zeros = 0;
    SET @ones = 0;
    SET @total = 0;
    SET @atted = 0;
    
    
    (SELECT (8-SUM(h1)+SUM(h2)+SUM(h3)+SUM(h4)+SUM(h5)+SUM(h6)+SUM(h7)+SUM(h8)) INTO @zeros FROM attentance WHERE StudID=NEW.StudID);
    (SELECT SUM(h1+h2+h3+h4+h5+h6+h7+h8) INTO @ones FROM attentance WHERE StudID=NEW.StudID);
    (SELECT (SUM(8-(h1+h2+h3+h4+h5+h6+h7+h8))+ SUM(h1+h2+h3+h4+h5+h6+h7+h8)) INTO @total FROM attentance WHERE StudID=NEW.StudID);
    
    SELECT (((@zeros-@ones)/@total)/100) INTO @atted FROM (SELECT 1) AS x;
    
    END$$
    
    0 讨论(0)
提交回复
热议问题