在MYSQL中创建一个BEFORE INSERT TRIGGER

时间:2016-11-10 06:34:24

标签: mysql

我需要帮助在mySQL Bench上创建一个BEFORE INSERT TRIGGER。我是新来的。

CREATE TABLE `quincyninying`.`toytracking` (
`Toyid` INT NOT NULL,
`ToyName` VARCHAR(50) NULL,
`Toycost` DECIMAL NULL,
`ToyAction` VARCHAR(50) NULL,
`ActionDate` DATETIME NULL,
 PRIMARY KEY (`Toyid`));

CREATE TABLE `quincyninying`.`toy` (
`Toyid` INT NOT NULL,
`ToyName` VARCHAR(50) NULL,
`Toycost` DECIMAL NULL,
PRIMARY KEY (`Toyid`));

在玩具桌上创建一个BEFORE INSERT触发器,用于将记录添加到玩具跟踪表中,其中包含来自INSERTED的玩具表记录中的信息,将是“INSERT”的硬编码ToyAction以及记录的当前日期和时间插入。

ERROR 1054: Unknown column 'inserted' in 'NEW' SQL Statement:
CREATE DEFINER = CURRENT_USER TRIGGER `quincyninying`.`toy_BEFORE_INSERT` BEFORE INSERT ON `toy` 
FOR EACH ROW
BEGIN
    IF new.inserted THEN
        SET @toyaction = 'DELETE';
    ELSE 
        SET @toyaction = 'NEW';
    END IF;

    INSERT INTO `quincyninying`.`toytracking` (toyId, ToyName, ToyCost,     Toyaction, ActionDate)
    VALUES       (new.toyid, new.Toyname, new.Toycost,@Toyaction, now());

END

它给我一个错误说"错误1054:未知列'已插入'在'新' "

2 个答案:

答案 0 :(得分:1)

取消IF new.inserted测试,因为没有具有该名称的列,只需硬编码INSERT作为您在要求中说明的ToyAction列的值。

CREATE DEFINER = CURRENT_USER TRIGGER `quincyninying`.`toy_BEFORE_INSERT` BEFORE INSERT ON `toy` 
FOR EACH ROW
BEGIN
    INSERT INTO `quincyninying`.`toytracking` (toyId, ToyName, ToyCost, Toyaction, ActionDate)
    VALUES (new.toyid, new.Toyname, new.Toycost, 'INSERT', now());
END

答案 1 :(得分:0)

试试这个:

DELIMITER $$

CREATE
    TRIGGER toy_before_insert BEFORE INSERT 
    ON toy
    FOR EACH ROW BEGIN
        IF NEW.Toyaction THEN
            SET @Toyaction = 'DELETE';
        ELSE
            SET @Toyaction = 'NEW';
        END IF;

        INSERT INTO toytracking (toyId, ToyName, ToyCost, Toyaction, ActionDate) VALUES (NEW.Toyid, NEW.ToyName, NEW.ToyCost, @Toyaction, NOW());

END$$

DELIMITER ;