MySQL Trigger on after insert

后端 未结 4 525
别那么骄傲
别那么骄傲 2020-12-14 17:25

I am new to MySQL. I have two tables total_loaner and available_loaner. I am trying to create a trigger for every new row added in total_loaner, I would to add that new row

相关标签:
4条回答
  • 2020-12-14 17:49

    You probably need to set your delimiter:

    DELIMITER $$
    
    CREATE TRIGGER new_loaner_added 
    AFTER INSERT ON `total_loaner` for each row
    begin
    INSERT INTO available_loaner (Kind, Type, Sno, Status)
    Values (new.Kind, new.Type, new.Sno, 'Available');
    END$$
    
    DELIMITER ;
    

    Right now, it's confusing the semi-colon at the end of the INSERT statement with the end of the CREATE TRIGGER statement.

    0 讨论(0)
  • 2020-12-14 17:51

    This one worked for me, more simplified version..

    CREATE TRIGGER new_loaner_added 
        AFTER INSERT ON `DB1`.`table_name`
        FOR EACH ROW 
          INSERT INTO `DB2`.`table_name` (messageID, conversationID, fromJID)
          VALUES (NEW.messageID,NEW.conversationID, NEW.fromJID);
    
    0 讨论(0)
  • 2020-12-14 18:15

    In your case you can rewrite your trigger like this

    CREATE TRIGGER new_loaner_added 
    AFTER INSERT ON total_loaner
    FOR EACH ROW 
      INSERT INTO available_loaner (Kind, Type, Sno, Status)
      VALUES (NEW.Kind, NEW.Type, NEW.Sno, 'Available');
    

    Note:

    • single quotes removed from table name total_loaner, because quotes effectively makes it a string literal instead of a proper identifier. You can use back ticks if you want but it's unnecessary since it's not a reserved word and it don't contain any special characters.
    • since it's a one-statement trigger now you don't need to use DELIMITER command and BEGIN...END block

    Here is SQLFiddle demo

    0 讨论(0)
  • 2020-12-14 18:15
    AFTER INSERT ON `total_loaner`
    

    Use backticks.

    0 讨论(0)
提交回复
热议问题