22

我是 MySQL 新手。我有两张桌子total_loaneravailable_loaner. 我正在尝试为添加的每个新行创建一个触发器total_loaner,我还想将该新行添加到available_loaner.

我的表格如下所示:

CREATE TABLE `total_loaner` (
  `Kind` varchar(10) NOT NULL,
  `Type` varchar(10) NOT NULL,
  `Sno` varchar(10) NOT NULL,
  PRIMARY KEY (`Sno`)
)

CREATE TABLE `available_loaner` (
  `Kind` varchar(10) NOT NULL,
  `Type` varchar(10) NOT NULL,
  `Sno` varchar(10) NOT NULL,
  `Status` char(10) NOT NULL DEFAULT '',
  PRIMARY KEY (`Sno`)
) 

我的触发器似乎不起作用。

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;
4

4 回答 4

30

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

于 2013-09-10T22:16:06.257 回答
8

您可能需要设置分隔符:

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 ;

现在,将INSERT语句末尾的分号与语句末尾混淆了CREATE TRIGGER

于 2013-09-10T20:54:34.443 回答
6

这个对我有用,更简化的版本..

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);
于 2016-08-11T09:54:56.113 回答
0
AFTER INSERT ON `total_loaner`

使用反引号。

于 2013-09-10T20:55:15.313 回答