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,
No, it’s not possible, unfortunately, nor you can pass NEW and OLD as parameters, nor function parameters can be OUT or INOUT (i.e. writable), so the short answer is no.
You can call a function from a trigger (provided the function doesn’t violate any of the MySQL trigger restrictions such as modifying the table the trigger is attached to), but you’ll have to pass the function every individual NEW or OLD field you need to read, and the function will be unable to write to them — all you can do from a function is return a value.