1

In my schema I have many tables with common fields that I need to fill. This are basicaly control fields like this ones:

id_db_user
date_creation
date_last_update

I have done two triggers to fill this fields:

-- Trigger DDL Statements
delimiter |
CREATE TRIGGER control_insert BEFORE INSERT ON EZT_SOCIETIES

  FOR EACH ROW BEGIN

    SET NEW.id_db_user    = current_user;

    SET NEW.date_creation = current_timestamp;

  END;
| delimiter ;


delimiter |
CREATE TRIGGER control_update BEFORE UPDATE ON EZT_SOCIETIES

  FOR EACH ROW BEGIN

    SET NEW.date_last_update = current_timestamp;

  END;
| delimiter ;

My question is: Can I write some function to call the operations inside the trigger? Something like this:

function fn_control_insert
    SET NEW.id_db_user    = current_user;
    SET NEW.date_creation = current_timestamp;

and then call this function in the trigger like:

delimiter |
CREATE TRIGGER control_insert BEFORE INSERT ON EZT_SOCIETIES

  FOR EACH ROW BEGIN

    call fn_control_insert;

  END;
| delimiter ;

This is possible to do in MySQL?

Best Regards,

4

2 回答 2

3

不,这是不可能的,不幸的是,你也不能将 NEW 和 OLD 作为参数传递,函数参数也不能是 OUT 或 INOUT(即可写),所以简短的回答是否定的。

您可以从触发器调用函数(前提是该函数不违反任何 MySQL 触发器限制,例如修改触发器附加到的表),但您必须将函数传递给每个单独的 NEW 或 OLD 字段需要读取,并且函数将无法写入它们 - 您可以从函数中做的所有事情就是返回一个值。

于 2012-06-06T08:25:24.227 回答
0
  • date_creation使用“ON UPDATE CURRENT_TIMESTAMP”子句将字段声明为 TIMESTAMP。该字段将使用 INSERT 或 UPDATE 语句中的 CURRENT_TIMESTAMP 值自动更新。更多信息 - TIMESTAMP 的自动初始化和更新

  • 在触发器中设置 NEW.id_db_user 值control_insert- SET NEW.id_db_user = current_user;

  • 移除control_update触发器。

于 2012-06-06T08:49:33.030 回答