MySQL 在插入后触发 [英] MySQL Trigger on after insert

查看:24
本文介绍了MySQL 在插入后触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 also like to add that new row to 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`)
) 

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

My trigger does not seem to work.

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;

推荐答案

在你的情况下,你可以像这样重写触发器

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');

注意:

  • 从表名total_loaner中删除单引号,因为引号有效地使其成为字符串文字而不是正确的标识符.如果需要,您可以使用反勾号,但这是不必要的,因为它不是保留字,也不包含任何特殊字符.
  • 因为它是一个单语句触发器,所以现在你不需要使用 DELIMITER 命令和 BEGIN...END
  • 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

这是SQLFiddle演示

Here is SQLFiddle demo

这篇关于MySQL 在插入后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆