如何将触发器 'if inserting' 从 oracle 转换为 mysql

how to convert trigger 'if inserting' from oracle to mysql

我一直在尝试将触发器从 oracle 转换为 MySQL/MariaDB。我在 MySQL 还是新人,所以我还在琢磨。

这是我正在执行触发器的 table 中的 table 结构:

CREATE TABLE `attendance` (
  `attendanceid` varchar(10) NOT NULL,
  `studentname` varchar(50) DEFAULT NULL,
  `classname` varchar(20) DEFAULT NULL,
  `status` varchar(20) DEFAULT NULL,
  `atdate` varchar(20) DEFAULT NULL,
  `classid` varchar(20) DEFAULT NULL
)

我已经为触发器创建了一个序列 table,如下所示:

CREATE TABLE `att_seq` (
  `id` int(11) NOT NULL
)

这是来自 oracle 的代码:

CREATE OR REPLACE TRIGGER "STUDENT"."CLASSID" 
BEFORE INSERT ON attendance
FOR EACH ROW
declare
BEGIN
 if :new.attendanceid is null then
                  select 'ATT' || attandance_seq.nextval into :new.attendanceid from dual;

    if inserting then
            if(:new.classname = '4A') then
            :new.classid := 'CLASS401';
            end if;
            if(:new.classname = '4B') then
            :new.classid := 'CLASS402';
            end if;
             if(:new.classname = '4C') then
            :new.classid := 'CLASS403';
            end if;
    end if;
  end if;
END;
/

到目前为止,这是我转换它的方式(p/s:'update class..' 代码是我从 oracle 代码添加的新代码):

DELIMITER $$
CREATE TRIGGER att_auto_id
BEFORE INSERT ON attendance
FOR EACH ROW
BEGIN
  INSERT INTO att_seq VALUES (NULL);
  SET NEW.attendanceid = CONCAT('ATT', LPAD(LAST_INSERT_ID(), 3, '00'));
  
  IF inserting THEN
    IF new.classname = `4A` THEN
        SET new.classid = `CLASS401`;
        UPDATE class 
        SET classid = new.classid;
    END IF;
    IF new.classname = `4B` THEN
        SET new.classid = `CLASS402`;
        UPDATE class 
        SET classid = new.classid;
    END IF;
    IF new.classname = `4C` THEN
        SET new.classid = `CLASS403`;
        UPDATE class 
        SET classid = new.classid;
    END IF;
  END IF;
END $$ 

当我 运行 它时,我得到这个错误:

1054 - 'field list'

中的未知列 'inserting'

如果有人能帮助我,我将不胜感激。先谢谢你:)

Oracle 触发器中的 inserting 关键字可帮助您确定触发器是否由插入操作调用,因为在 Oracle 中您可以定义一个触发器以供多个事件调用(例如,在插入或更新之前) .

然而,在mysql中,触发器只能由单个事件调用,因此在mysql中不需要这个关键字。只需在您的代码中不包含 if inserting then 条件即可。

此外,在 table 中格式化序列值是错误的 - 要么在应用程序中显示值时格式化值,要么在声明列时使用 zerofill 属性。这样您就可以直接在 table.

中使用 auto_increment 列

序列 table 的声明缺少 auto_increment 属性。该字段也声明为 not null,因此您不能使用 null 生成新的 auto_increment 值。使用可空字段或空值子句。

此外,我认为您也应该删除所有 update class 语句。这些语句将无条件更新 class table 中所有记录的 classid 字段。